Express从Axios POST读取空白主体,尽管使用了中间件?

ttisahbt  于 2022-11-23  发布在  iOS
关注(0)|答案(1)|浏览(144)

我正在尝试从React应用程序发布到我制作的Express API。
使用Postman,我可以使用“x-www-form-urlencoded”很好地发布数据。
我也尝试过在React应用程序中执行同样的操作,但是每次API读取req.body时,它都是空白的和未定义的。当我从React应用程序端console.log()请求主体和头部时,它们显示数据。但是从API的Angular 控制台记录请求主体时,它是空白的。
相关API代码:

var sql = require("mssql");
var express = require('express');
var app = express();
var cors = require('cors');
require('dotenv').config({ path: './secrets.env' });
app.use(cors());

app.use('/longhorns/add', express.urlencoded({extended: true}));

 app.post('/longhorns/add', function (req, res) {

  sqlRequest(res, "EXEC AddLonghorn @Name = '" + req.body.Name + "', @RanchPrefix = '" + req.body.RanchPrefix + "', @RoleID = " + parseInt(req.body.RoleID) + ", @SexID = " + parseInt(req.body.SexID) + ", @FatherLonghornID = " + parseInt(req.body.FatherLonghornID) + ", @MotherLonghornID = " + parseInt(req.body.MotherLonghornID) + ", @ReferenceNumber = '" + req.body.ReferenceNumber + "', @DOB = '" + req.body.DOB + "', @Description = '" + req.body.Description + "'");
 });

相关React应用程序代码:

let submitLonghorn = async (e: any) => {
    e.preventDefault();
    
    const longhorn = {
      name,
      ranchPrefix,
      roleID,
      sexID,
      fatherLonghornID,
      motherLonghornID,
      referenceNumber,
      dob,
      description
    }

    const config = {
      headers: {
        'Content-Type': 'appliation/x-www-form-urlencoded'
      }
    }

    axios.post('http://127.0.0.1:8081/longhorns/add', longhorn, config)
    .then(() => console.log("Longhorn added"))
    .catch(err => {console.error(err)});

  };

我尝试手动将Axios头文件设置为x-www-form-urlencoded,但没有效果,并确保将API应用程序设置为使用Express附带的中间件。我还尝试了另一个帖子的建议,将app.use(express.X())语句更改为express.json()[同时也将axios请求更改为不是x-www-form-urlencoded],但没有任何区别。

qc6wkl3g

qc6wkl3g1#

不完全确定这是所有的问题,但您需要从async方法返回您的承诺,否则它可能会在完成之前终止。请尝试:

let submitLonghorn = async (e: any) => {
   e.preventDefault();
   
   const longhorn = {
     name,
     ranchPrefix,
     roleID,
     sexID,
     fatherLonghornID,
     motherLonghornID,
     referenceNumber,
     dob,
     description
   }

   const config = {
     headers: {
       'Content-Type': 'appliation/x-www-form-urlencoded'
     }
   }

try {
   return axios.post('http://127.0.0.1:8081/longhorns/add', longhorn, config)
  } catch(err) {
    console.error(err);
  }
}

相关问题