【问题标题】:req.body is empty in express when sending JSON string in http request在 http 请求中发送 JSON 字符串时,req.body 为空
【发布时间】:2020-12-02 16:51:17
【问题描述】:

Express 收到一个空的 json 字符串 {},我无法弄清楚原因。我已经为 json 解析器尝试了 bodyParser 和 express.json 并得到了相同的结果。我也找不到我的标题有什么问题。下面是相关代码:

HTTP 客户端发送请求

    private sendRequest<T>(verb: string, url: string, body?: any)
    : Observable<T> {

    let myHeaders = new HttpHeaders();
   // myHeaders = myHeaders.set("Access-Key", "<secret>");
    // myHeaders = myHeaders.set("Application-Names", ["Rapid Recipes", "MSsanto"]);
    

    
    return this.http.request<T>(verb, url, {
      body: JSON.stringify(body), headers: myHeaders })
      .pipe(catchError((error: Response) => throwError(`Network Error: ${error.statusText} (${error.status})`)));

  }

快递应用

   var app = express();
//app.use(bodyParser());
//app.use(bodyParser.json({ limit: 'Smb' }));
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());

 app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
  res.setHeader('Access-Control-Allow-Methods', 'GET','POST','OPTIONS','PUT','PATCH','DELETE',);
  res.setHeader('Access-Control-Allow-Headers', 'Authorization', 'X-Requested-With, Content-Type', 'application/x-www-form-urlencoded', 'application/json');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();

 
app.post("/:type", function (req, res) {
  console.log('The POST was received');
  
  var typeName = req.originalUrl.substring(1).toLowerCase();
  var params = {};
  params[typeName] = 1;
  params["_id"] = 1


 console.log("the request bod is " + JSON.stringify(req.body)); //this returns {}
  

  var dbm = dbModel.findOne({}, params);

 
  dbm.updateOne({ $push: { "recipe": req.body } }, function (err, data)

  {

    if (err) {
      res.send(err);

    }

    else {
      res.send(data)
      console.log('data saved!');

    } } ) }
  )
});

【问题讨论】:

    标签: json angular express


    【解决方案1】:

    您没有在请求标头中发送内容类型。

    myHeaders = myHeaders.set("Content-Type", "application/json");
    

    【讨论】:

    • 我厌倦了,但是当我将它设置为 application/json 时它返回内部服务器错误 500
    • 500 错误的文本是什么?那应该指出实际的错误。
    • 我能够捕捉到错误。实际上不是500。它与CORS有关。 “从源 'localhost:4200' 访问 XMLHttpRequest 在 'localhost:3000/Recipe' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。zone-evergreen.js: 2845 POST localhost:3000/Recipe net::ERR_FAILED
    • 我能够通过按照您的建议设置标题并将以下行添加到 express 应用程序来解决问题: var cors = require('cors'); app.use(cors());
    猜你喜欢
    • 2016-03-28
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 2012-08-15
    • 2018-06-02
    相关资源
    最近更新 更多