反应 axios 上的 CORS,但不是香草

Posted

技术标签:

【中文标题】反应 axios 上的 CORS,但不是香草【英文标题】:CORS on react axios, but not on vanilla 【发布时间】:2021-12-25 18:14:18 【问题描述】:

我正在尝试使用 React/axios 从 AWS 端点获取数据,但是当我尝试发出请求时,我收到了这个 CORS 错误:

从源“http://localhost:3000”访问“https://myAWS.com/login”处的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头请求的资源。

当我尝试构建托管的 github 页面时,我也遇到了同样的错误。但是当我在另一个托管网站上使用 Vanilla js 时它可以工作,我在 axios 上发送的请求是否错误?

香草

let body = 
    "name": "Bbbb 202",
    "email": "bbbb2220@bob.com",
    "password": "122",
    "wallet": "bbbbB202222"
  ;
  
  var http = new XMLHttpRequest();
  var url = 'https://myAWS.com/login';
  http.open('POST', url, true);

  //Send the proper header information along with the request
  http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

  http.onreadystatechange = function() //Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) 
      alert(http.responseText);
    
  
  http.send(body);

反应

async SendRequest(method, url, callback, body)       
    axios.request(
        method: 'POST',
        data: JSON.stringify(body),
        headers: 
            "Content-Type": "application/json;charset=utf-8",
            "Authorization": "Bearer " + localStorage.getItem("token"),
        ,
        url: url
    ) 
    .then(response => 
        console.log(response);
        callback(
            status: response.status,
            data: response.data,
        );
    )
    .catch(err => 
        console.log(err);
        callback(
            status: err.status,
            data: err,
        );
    );

【问题讨论】:

这是因为您需要在标题中启用 CORS。添加:'Access-Control-Allow-Origin': '*',same-origin 到您后端的标题中。注意:这会在您的服务器中打开一个安全漏洞,因此请在使用之前对其进行充分研究。 但是如果是后端的问题,香草版本也不能正常工作吗? 【参考方案1】:

这些不是同一个请求。 “香草”请求看起来可能符合所谓的“安全请求”。要成为安全请求,content-type 必须是 application/x-www-form-urlencoded(或其他 2 个),并且不能使用任何受限的 HTTP 方法。

我也在这里写了更多关于它的文章:https://evertpot.com/no-cors/

【讨论】:

不错!!这正是我需要知道的thx

以上是关于反应 axios 上的 CORS,但不是香草的主要内容,如果未能解决你的问题,请参考以下文章

在 Django 中使用 Axios 和 CORS 获取 POST 请求的错误请求并做出反应

带有反应应用程序的 POST 上的 ASP.NET CORS 异常

反应 Axios 输入未定义

如何将香草转换为反应钩子切换菜单

如何在反应项目和 Firebase 中使用带有 axios 的删除请求?

使用 fetch API 的 CORS 错误 - 反应创建应用程序