簡體   English   中英

我的 POST 有什么問題,導致 req.body 為空

[英]What is wrong with my POST, resulting in an empty req.body

我正在構建一個簡單的 MySQL、Express、Angular、Node 應用程序,並使用 Sequelize 作為我的 ORM。 當我創建一個新調查時,我發送的值沒有被設置,因為 req.body 是一個空對象。

服務器.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);
});

應用程序.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;
};

路由.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);
    })
},

我最近在這里遇到了類似的問題: 為什么我的 req.body 在 POST 時總是空的? 但解決方案對這個問題不起作用。 我假設它是相似的,但到目前為止解決方案已經暗示了我。

不需要字符串化

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

根據上面的許多評論(非常感謝所有人),我通過將 bodyParser 實現從

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

app.use( bodyParser.json() );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM