繁体   English   中英

在 http 请求中发送 JSON 字符串时,req.body 为空

[英]req.body is empty in express when sending JSON string in http request

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!');

    } } ) }
  )
});

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM