POST请求由于CORS错误而在rea​​ct axios中被阻止 [英] POST request blocked in react axios due to CORS error

查看:401
本文介绍了POST请求由于CORS错误而在rea​​ct axios中被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向包含多部分数据的API发送POST请求.

I am trying to send a POST request to an API with multipart data.

我在邮递员中测试了API,并且在邮递员中一切正常.但是,当我在反应中调用API时,它给了我CORS错误.

I test the API in postman and everything works fine in Postman. But when I call the API in react, it gives me CORS error.

我交叉检查了URL,标题和数据,对我来说一切似乎都不错.我在同一个主题上经历了多个堆栈溢出"问题,发现我需要将allow-cross-origin与标头一起传递.我在标题中添加了它,但无法解决我的问题.

I cross-checked the URL, Header, and Data, all seems OK for me. I go through multiple Stack Overflow question on the same topic and found that I need to pass allow-cross-origin along with the header. I added that in my header but didn't able to solve my problem.

我在控制台中看到的错误是:

The error which I got in the console is:

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);
      }
    })
}

我以前将其导入到组件中,然后通过form-submit方法调用它.

I used to import this in my component and call it on the form-submit method.

推荐答案

axios调用无法解决CORS. 服务器的响应必须具有"Access-Control-Allow-Origin": "*"

axios call with that header in React doesn't solve CORS. Server's response must have "Access-Control-Allow-Origin": "*"

检查网络标签并查看服务器的响应.

check network tabs and see server's response.

这篇关于POST请求由于CORS错误而在rea​​ct axios中被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆