testingREST API – req.body undefined(Node.js / Express / Mocha / Supertest)

我正在尝试testingNode中构build的REST API。 我用Postman手工testing了这个API,没有问题,但是我用Mocha / Chai / Supertest编写testing时遇到了麻烦。

当我尝试testing发送到路由时,请求主体是未定义的。 在我迄今为止的研究中,似乎无法find与我正在做的和其他人有任何有意义的区别,但由于某些原因,我尝试发送的数据没有通过。

以下是路线的处理方式:

router.route('/media') .post(RouteController.postMedia); RouteController.postMedia = function(req, res) { var media = new Media(); console.log(req.body); media.title = req.body.title; media.type = req.body.type; media.tags = req.body.tags; media.pubdate = req.body.pubdate; media.editdate = req.body.editdate; media.filename = req.body.filename; media.extension = req.body.extension; media.description = req.body.description; media.save(function(err) { if (err) res.send(err); res.json({ message: 'File added!', data: media }); }); }; 

这是我的testing:

  var request = require('supertest'), should = require('chai').should(), express = require('express'), mongoose = require('mongoose'), app = express(); require('../api/routes')(app); var db = require('./config/db'); describe('API Routing', function() { before(function(done) { mongoose.createConnection(db.url); done(); }); describe('Media', function () { it('should add new photo to database with call to POST /api/v1/media', function(done) { var photo = { title: 'Test Photo', type: 'photo', tags: ['test', 'test2', 'asdf'], filename: 'test-photo.jpg', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' }; request(app) .post('/api/v1/media') .send(photo) .end(function(err, res) { if (err) { throw err } res.status.should.equal(200); done(); }); }); }); 

当我运行testing时,我得到错误TypeError: Cannot read property 'title' of undefined因为req.body是未定义的。 console.log(req.body); 部分证实了req.body是未定义的。

这里有两种可能(好的,一个确定的和一个可能的):

首先,你需要告诉supertesttypes你正在发送types的JSON(或任何其他types的发送)。

  request(app) .post('/api/v1/media') .type('json') .send(photo) 

其次,你有一个bodyParser设置在节点中吗? 不知道你正在使用什么框架,但他们都需要某种forms的身体parsing,无论是内置的或外部的。 https://www.npmjs.com/package/body-parser

我也面临同样的问题。 我已通过添加以下行来解决此问题:

app.use(bodyParser.json());