繁体   English   中英

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

[英]CORS on react axios, but not on vanilla

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

从源 'http://localhost:3000' 访问 XMLHttpRequest at 'https://myAWS.com/login' 已被 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,
        });
    });
}

这些不是同一个请求。 “vanilla”请求看起来可能符合所谓的“安全请求”。 要符合安全请求的条件,内容类型必须是application/x-www-form-urlencoded (或其他 2 个),并且不使用任何受限制的 HTTP 方法。

我也在这里写了更广泛的内容: https : //evertpot.com/no-cors/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM