我正在尝试做一些非常简单的事情,下面是我的代码:
// in react
async function postAxios_product(formData) {
// formdata is a string, for example "WWWWWWW", from clicking on an input
try {
const obj2post = {name:formData}
console.log("post to api/product:" + JSON.stringify(obj2post)) // shows {"name":"WWWWWWW"} for example
await axios.post(`${server}/product`, obj2post, {"Access-Control-Allow-Origin":"*"} )
.then(set_products( [...get_products, obj2post])) // update react state
}
catch (e) {console.error('Error in postAxios_product' + e.message);}
}
// in express node
app.post(`/product`, async (req, res) => {
console.log("inside post product")
console.log(req.data) // undefined
console.log(req.body) // undefined
console.log(req.request) // {}
console.log(req.params) // {}
let product = await Product.create(req.data);
return res.status(201).send({ error: false, product })
})
我在Axios中查找了后端请求参数未定义的答案,请参阅req.query、req.data等
我也试过:
const {data: json} = await axios.post(`${server}/product`, obj2postStr, {"Access-Control-Allow-Origin":"*"} )
如Node receive post json from axios post中所建议的,但也不起作用
您可能需要在nodejs服务器上安装并使用bodyParser
首先在服务器文件夹上运行npm i body-parser
然后require
body-parser
进入您的服务器文件
const bodyParser = require("body-parser");
然后在初始化你的应用程序后添加这2行
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
这应该允许您通过访问req.body
来访问请求主体
尝试将cors和body解析器添加到express应用程序中,这有助于request
映射/解析
...
app.use(cors())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())