【问题标题】:What is wrong with my POST, resulting in an empty req.body我的 POST 有什么问题,导致 req.body 为空
【发布时间】:2017-06-12 13:32:59
【问题描述】:

我正在构建一个简单的 MySQL、Express、Angular、Node 应用程序,并使用 Sequelize 作为我的 ORM。当我创建一个新调查时,我发送的值没有设置,因为 req.body 是一个空对象。

server.js

'use strict';

var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var bodyParser = require('body-parser');
var models = require('./server/models/');
var routes = require('./server/routes');

app.use(bodyParser.urlencoded({ 
  extended: true 
}));
app.use(express.static(process.cwd() + '/public'));

//App routes
app.use(routes(express.Router()));

app.get('/*', function (req, res) {
  res.sendFile('index.html', {
    root: './public'
  });
});

app.listen(port, function() {
    console.log('Server running on port %s ', port);
});

app.js

'use strict';

// Declare app level module which depends on views, and components
var app = angular.module('myApp', []);

    app.controller('SurveyController', ['$scope', '$http', function($scope, $http) {

    //Get all Surveys
    $http.get("/surveys")
    .then(function(response) {
        $scope.surveys = response.data;
    });

    $scope.create = function() {
      $http.post("/surveys",{
        question: $scope.question, 
        answers: $scope.answers,
        user: $scope.user
      })
      .then(function(response) {

      });
    }
}]);

型号

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Survey = sequelize.define('Survey', {
    question: DataTypes.STRING,
    answers: DataTypes.STRING,
    user: DataTypes.STRING
  }, {
     underscored: true,
     classMethods: {
       associate: function(models) {
         // associations can be defined here
       }
     }
  });
return Survey;
};

routes.js

var surveys = require('./controllers/surveys');

module.exports = function (router) {
  //routes
  router.get('/surveys', surveys.get);
  router.get('/surveys/:id', surveys.getOne);
  router.post('/surveys', surveys.create);
  router.put('/surveys', surveys.update);
  router.delete('/surveys', surveys.delete);

  return router
};

控制器

//Create a new survey
create: function(req, res) {
    //this req.body and req.params are both empty
    Survey.create(req.body)
    .then( function(newSurvey) {
        res.status(200).json(newSurvey);
    })
    .catch( function(error) {
        res.status(500).json(error);
    })
},

我最近在这里遇到了类似的问题:Why is my req.body always empty on POST? 但解决方案不适用于此问题。我假设它是相似的,但到目前为止,解决方案已经暗示了我。

【问题讨论】:

  • 你在用body-parser吗?
  • 确保您使用的是app.use(express.bodyParser()); 中间件。
  • 您似乎没有使用bodyParser.json()
  • 感谢@Phil,我将 bodyParser 实现更改为使用 json 而不是 urlencoded

标签: javascript mysql angularjs node.js sequelize.js


【解决方案1】:

不需要字符串化

$http
  .post("/surveys", {
     question: $scope.question, 
     answers: $scope.answers,
     user: $scope.user
   },
   {
     headers: { 'Content-Type': 'application/json; charset=UTF-8'}
   })

【讨论】:

  • 抱歉,这是我试图解决的问题之一,但我忘了恢复(现已编辑)。现有的代码就是你贴出来的,req.body是空的
  • 如何添加标题:{ 'Content-Type': 'application/json; charset=UTF-8'}
  • 默认的 Angular 内容类型标头已经是 application/json
  • 是的,你是对的。该问题似乎与您的服务器端代码有关。如果请求发送正确,打开 chorome 控制台并检查网络
  • 我觉得肯定是服务端代码。网络在 POST 上显示状态代码 200
【解决方案2】:

对于上面的许多 cmets(非常感谢大家),我通过更改我的 bodyParser 实现来解决这个问题

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

app.use( bodyParser.json() );

【讨论】:

  • 那么你为什么首先使用urlencoded
  • 因为数据是通过表单提交的,我的理解是这样用的
猜你喜欢
  • 2017-06-11
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
相关资源
最近更新 更多