Подтвердить что ты не робот

Node.js/Экспресс/Mocha/Supertest Rest API - Пустое тело запроса

Я везде искал, чтобы найти решение этого. Единственное, что я нашел, - это неотвеченный пост. Прошу прощения, если я что-то пропустил.

Проблема в том, что когда я пытаюсь получить значения POST в API /createQuestion, тело пустое /undefined. Я получаю такие ошибки, как Cannot read proprety 'question' of undefined, исходящие из API.

Экспресс-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 в тело запроса?

4b9b3361

Ответ 1

Возможно, ваше приложение не использует промежуточное программное обеспечение bodyParser.

app.use(express.bodyParser());

Из документов expressjs:

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

});