正文解析器不允许localhost加载NODE

时间:2016-12-22 22:47:14

标签: javascript node.js bash express

var express = require('express');
var app = express();
var bodyParser = require('body-parser'); 




//PROBLEM LINE
    **app.use(parser.json);**
///////////////    




var todos = [];
var nextTodoItem = 1;
app.use(bodyParser.json);


app.get('/', function(req, res){
    //console.log("ToDo Root");
    res.send("ToDo Root");
});

//GET REQUEST TO GET ALL TODO ITEMS
        //   GET /todos

app.get('/todos', function (req, res) {
    // Need to send back the array of todos
    res.json(todos); //array is converted to JSON.
    }

);

//GET REQUEST TO GET SOME SPECIFIC TODO
        //GET todos/:id
                //Express uses : (colon) to parse data.

app.get('/todos/:id', function (req, res) {
    var todoID = parseInt(req.params.id, 10);
    var todoObjectWithID = -1;
    todos.forEach(function (todo) {
        if(todo.id == todoID){
            todoObjectWithID = todos[todoID - 1];

        }
    });

    if(todoObjectWithID == -1){
        res.status(404).send();


    } else {
        res.json(todoObjectWithID); //Send the JSON of the specific todo with id requested.
    }
    console.log('Asing for todo with id of ' + req.params.id);
});


//Create a POST request to create new TODO Items.

        //POST /todos
app.post('/todos', function(req, res){
    var body = req.body;
    console.log("description");
    res.json(body);

});




//Server basic start up (port and log)

app.listen(3000, function () {
    console.log("Server up and running");
});

我使用bash(Mac OS)运行服务器,但是我转到http://localhost:3000没有任何加载,但当我删除app.use(bodyParser)时,它正确加载。

正文解析器有什么问题?

只有拥有该行时才会出现此问题,否则,服务器运行完全正常。我需要那个解析器,所以我的选择是什么?

1 个答案:

答案 0 :(得分:1)

将该行更改为app.use(bodyParser.json());