简体   繁体   中英

NODE.JS Routing issue while following angular fundamental course

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);
};

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) => {
    fs.readFile('app/data/event/' + req.params.id + '.json', 'utf8', (err, json) => {
      // If an error occurred reading the file
      // send back a 500 INTERNAL SERVER ERROR
      if (err) return res.sendStatus(500);

      // Return a JSON response
      // automatically sets Content-Type to application/json
      return res.json(json);
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM