简体   繁体   English

Express.js req.body 什么都不返回

[英]Express.js req.body is returning nothing

I am learning node and express to create an api for an angular app I will be creating.我正在学习 node 并表示为我将创建的 angular 应用程序创建 api。

When I try and post something the req.body seems to be blank.当我尝试发布一些内容时, req.body似乎是空白的。

This is my server.js file这是我的 server.js 文件

'use strict';

var express = require('express'),
  app = express(),
  mongoose = require('mongoose'),
  router = require('./api'),
  bodyParser = require('body-parser');

mongoose.connect('mongodb://localhost/my_db');

app.use(bodyParser.json());
app.use('/api', router);

app.get('/', function(req, res) {
  res.render(__dirname + '/index.jade');
});

app.listen(3001, function() {
  console.log('Listening on port 3001');
});

and this is my api/index.js file:这是我的 api/index.js 文件:

'use strict';

var express = require('express'),
    Todo = require('../models/todo'),
    router = express.Router();

router.get('/todos', function(req, res) {
  Todo.find({}, function(err, todos) {
    if(err) {
      return console.log(err);
    }
    res.json({todos: todos});
  });
});

router.post('/todos', function(req, res) {
  var todo = req.body;
  res.json({todo: todo});
});


module.exports = router;

when I use postman to post this to http://localhost:3001/api/todos :当我使用邮递员将其发布到http://localhost:3001/api/todos

{
    'name': 'Walk the Dog',
    'completed': false
}

my response is:我的回答是:

{
  "todo": {}
}

I can't see why this would be blank, any help is appreciated.我不明白为什么这会是空白的,任何帮助表示赞赏。

UPDATE更新

Turns out I was posting text in postman instead of JSON .原来我是在 postman 而不是JSON发布text

use this in your server.js file在你的 server.js 文件中使用它

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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