req.body 未定义并使用 Angular 进行 Express API 测试

jhl*_*sin 4 mongoose express angularjs

我正在练习 API 并遇到一个小问题。有人可以看一下下面的代码并让我知道为什么当我在客户端使用 Angular $http 执行 POST 请求时 req.body 会记录 undefined 吗?还尝试一个简单的 jquery AJAX 请求以获得相同的结果。

//------------------  back-end
var express = require('express');
var mongoose = require('mongoose');
var app = express();

//connect DB
var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/Ecomm_db';
mongoose.connect(mongoURI);

//express config
app.use(express.static(__dirname + '/public'));

//DB setup
var Schema = mongoose.Schema;

var Product = new Schema({  
    title: { type: String, required: true },  
    description: { type: String, required: true },  
    style: { type: String, unique: true },  
    modified: { type: Date, default: Date.now }
});

var ProductModel = mongoose.model('Product', Product); 


//API
app.post('/api/products', function (req, res){
  var product;
  console.log("POST: ");
  console.log(req.body);
  product = new ProductModel({
    title: req.body.title,
    description: req.body.description,
    style: req.body.style,
  });
  product.save(function (err) {
    if (!err) {
      return console.log("created");
    } else {
      return console.log(err);
    }
  });
  return res.send(product);
});

//--------------------------- client-end
$http({
      method: 'POST',
      url: '/api/products',
      data: {
        title: "my t-shirts",
        description: "super good",
        style: "my style"
      }
    }).then(function (response){
      console.log('POST response',response);
    }, function (err){
      console.log('err:', err);
    })
Run Code Online (Sandbox Code Playgroud)

小智 5

尝试使用模块“body-parser”

var bodyParser = require('body-parser'); ... app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json());