【问题标题】:req.body undefined and express api testing using angularreq.body 未定义并使用 Angular 进行快速 API 测试
【发布时间】:2016-02-25 06:52:50
【问题描述】:

我正在练习 API 并遇到一个小问题。有人可以看看下面的代码,让我知道为什么当我在客户端使用 angular $http 进行 POST 请求时 req.body 记录未定义?还可以尝试一个简单的 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);
    })

【问题讨论】:

    标签: angularjs express mongoose


    【解决方案1】:

    尝试使用模块'body-parser'

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

    【讨论】:

    • 哦,海伦。你是拯救者。它修复了它。
    • @jhlosin 很高兴为您提供帮助
    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 2014-05-21
    • 2022-01-01
    • 2017-07-08
    • 2021-10-07
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多