javascript - NODE.JS Routing issue while following angular fundamental course -
when trying access url http://localhost:8000/data/event/1 getting error saying
cannot /data/event/1
my web server js code below , following have provided directory structure. looks routing problem i'm not able what's wrong.
i looking serve json file using node.
var express = require('express'); var path = require('path'); var events = require('./eventscontroller'); var app = express(); var rootpath = path.normalize(__dirname + '/../'); console.log(__dirname); var bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({extended: true})); app.use(bodyparser.json()); app.use(express.static( rootpath + '/app')); app.get('data/event/:id',events.get); app.post('data/event/:id',events.save); app.listen(8000); console.log('listening on port ' + 8000 + '...')
directory structure
demoapp app css data event 1.json 2.json scripts node_modules eventscontroller web-server
eventcontroller sample code
var fs = require('fs'); module.exports.get = function(req, res) { var event = fs.readfilesync('app/data/event/' + req.params.id + '.json', 'utf8'); res.setheader('content-type', 'application/json'); res.send(event); };
your problem way you've defined routes, need leading /
// incorrect app.get('data/event/:id',events.get); app.post('data/event/:id',events.save); // correct app.get('/data/event/:id',events.get); app.post('/data/event/:id',events.save);
one more comment on how you're reading file. wouldn't use fs.readfilesync()
within route. block entire server handling requests/responding until reading file complete. instead use async version , respond callback of fs.readfile()
.
module.exports.get = (req, res) => { fs.readfile('app/data/event/' + req.params.id + '.json', 'utf8', (err, json) => { // if error occurred reading file // send 500 internal server error if (err) return res.sendstatus(500); // return json response // automatically sets content-type application/json return res.json(json); }); };
Comments
Post a Comment