NODE.JS Routing issue while following angular fundamental course

By : Abhi9
Source: Stackoverflow.com
Question!

When trying to access URL http://localhost:8000/data/event/1 I am getting an error saying

Cannot GET /data/event/1

My web server js code is below and following it I have provided the directory structure. Looks to be a routing problem but I'm not able to what's wrong.

I am looking to 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 get 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);
};
By : Abhi9


Answers

Your problem is the way you've defined your routes, they need a 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 the file. I wouldn't use fs.readFileSync() within your route. This will block your entire server from handling requests/responding until reading the file is complete. Instead I would use the async version and then respond from the callback of fs.readFile().

module.exports.get = (req, res) =
By : peteb


This video can help you solving your question :)
By: admin