我到处找我能找到解决方法。我发现的唯一一件事是没有回复的帖子。如果我忽略了某些事情,我会道歉。
问题在于,当我尝试在POST
API中获取/createQuestion
值时,正文为空/未定义。我收到来自API的Cannot read proprety 'question' of undefined
错误。
Express API:
app.post("/createQuestion", function(req, res) {
var questionType = req.body.question.type;
var questionText = req.body.question.text;
var questionDuringClass = req.body.question.duringClass;
// Do a bunch of stuff
res.send(response);
});
测试:
var should = require('should');
var assert = require('assert');
var request = require('supertest');
var winston = require('winston');
request = request('http://localhost:8080');
describe('Questions', function() { // Test suite
before(function(done) {
done();
});
it('Should create a freeResponse question', function(done) { // Test case
var postData = {
"question" : {
"type" : "freeResponse",
"text" : "This is a test freeResponse question (automated testing)",
"duringClass" : "1"
}
};
request()
.post('/createQuestion')
.send(postData)
.expect(200)
.end(function(err, res) { // .end handles the response
if (err) {
return done(err);
}
done();
});
});
it('Should delete a freeResponse question', function(done) { // Test case
var postData = {
"question" : {
"type" : "freeResponse",
"text" : "This is a test freeResponse question (automated testing)",
"duringClass" : "1"
}
};
request()
.post('/deleteQuestion')
.send(postData)
.expect(200)
.end(function(err, res) { // .end handles the response
if (err) {
return done(err);
}
done();
});
});
我错过了什么? .send()
是否以某种不同格式发送POST
数据?是POST
它不是请求的主体吗?
答案 0 :(得分:28)
可能是您的应用未使用bodyParser中间件。
app.use(express.bodyParser());
来自expressjs docs:
req.body
此属性是包含已解析请求正文的对象。此功能由bodyParser()中间件提供,但其他正文解析中间件也可遵循此约定。使用bodyParser()时,此属性默认为{}。
这里有一个完整的例子
var express = require('express');
var request = require('supertest');
var assert = require('assert');
var app = express();
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.send('ok');
});
app.post('/createQuestion', function(req, res) {
var message = req.body.partA + ' ' + req.body.partB;
res.send(message);
});
describe('testing a simple application', function() {
it('should return code 200', function(done) {
request(app)
.get('/')
.expect(200)
.end(function(err, res){
if(err) {
done(err);
} else {
done();
}
});
});
it('should return the same sent params concatenated', function(done) {
request(app)
.post('/createQuestion')
.send({ partA: 'Hello', partB: 'World'})
.expect(200, 'Hello World')
.end(function(err, res){
if(err) {
done(err);
} else {
done();
}
});
});
});