首页 > 解决方案 > 由于 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);
      }
    })
}

我曾经在我的组件中导入它并在表单提交方法上调用它。

标签: reactjstypescriptaxioscors

解决方案


你必须像这样添加你的后端。(此示例为 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());

推荐阅读