【发布时间】:2021-09-18 23:53:45
【问题描述】:
当我在 axios.post 中设置数据时,出现 CORS 错误。如果我在没有参数数据的情况下设置 axios.post,它可以工作。 axios.get() 也一样,没有 CORS 错误
JS代码
btn.onclick = function () {
axios({
method:'post',
url:'http://localhost:3000/wrong',
data:{
user:'Joe',
age:10
}
}).then(response=>{
console.log(response);
});
};
nodeJS 代码
let express=require('express');
let app=express();
app.use(express.json());
app.post('/wrong',(req,res)=>{
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Aceess-Control-Allow-Headers", "*");
res.setHeader("Aceess-Control-Allow-Methods", "*");
const r=JSON.stringify(req.body);
res.send(r);
});
app.listen(3000,()=>{
console.log('3000 listening...');
});
【问题讨论】:
-
我用postman 用JSON 发送请求,后端没问题,不知道为什么-_-! axios.post 默认发送 JSON 对吧?