reactjs - 由于 CORS 错误,POST 请求在反应 axios 中被阻止
问题描述
我正在尝试向包含多部分数据的 API 发送 POST 请求。
我在邮递员中测试了 API,在邮递员中一切正常。但是当我在反应中调用 API 时,它给了我 CORS 错误。
我交叉检查了 URL、标题和数据,对我来说一切都很好。我经历了关于同一主题的多个 Stack Overflow 问题,发现我需要将 allow-cross-origin 与标题一起传递。我在标题中添加了它,但无法解决我的问题。
我在控制台中得到的错误是:
No 'Access-Control-Allow-Origin' header is present on the requested resource
API调用代码
import axios from 'axios';
const header = {
"userid":localStorage.getItem("userid"),
"token":localStorage.getItem("token"),
"Content-Type": "multipart/form-data",
"Access-Control-Allow-Origin": "*"
}
const URL="https://api.hello.com/dashboard/venue_updated";
export function updateVenue(data,name,venue_type,email, phone_no,callback, errorcallback){
console.log(header);
axios.post(URL,data,{
params:{
name,
venue_type,
email,
phone_no,
},
headers:header
})
.then(res => {
if(callback != null){
callback(res);
}
})
.catch(err => {
if(errorcallback != null){
errorcallback(err);
}
})
}
我曾经在我的组件中导入它并在表单提交方法上调用它。
解决方案
你必须像这样添加你的后端。(此示例为 nodejs)
app.use(cors(), function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // update to match the domain you will make the request from
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
启用所有 CORS 请求
app.use(cors());
推荐阅读
- java - 从数组中删除随机元素并将其添加到另一个数组:OutOfIndex 绑定错误
- javascript - 在 Javascript 中检测 base64 图像字符串中的恶意内容
- android - 扫描后如何连接到 Android 上的 Beacon?
- javascript - 你如何在 Javascript 中获得今天结束的 Unix 时间戳?
- node.js - 如何在 Node / pg-pool 中参数化 Postgres 数组值
- flutter - 如何正确使用 GetX 与 TextField 和一些服务器端验证?
- flutter - 如何根据 Flutter 中的条件启用/禁用 DropDownButton?
- php - Recaptcha v3 不工作 - 表单不提交
- php - json 解析 swift alamofire
- postgresql - 无法使用 Kafka JDBC Sink 连接器将数据加载到 Postgres