通过授权

时间:2017-11-13 10:36:31

标签: javascript reactjs

我想使用React JS做一个远程请求。我尝试按如下方式进行:

let username = 'some-username';
let password = 'some-password';
let url = 'some-url';
fetch(url', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic '+btoa(username + ":" + password),
    },
}).then(response => {
      debugger;
      return response.json();
}).then(json => {
      debugger;
});

我收到错误: enter image description here enter image description here

如果我使用与邮递员相同的凭据执行相同的请求,则可以使用:

enter image description here

有什么想法吗?

更新

let user = 'some-user';
let password = 'some-password';
let url = 'some-url';

let req = new XMLHttpRequest();
let body = '';

if ('withCredentials' in req) {
    req.open('GET', url, true);
    req.setRequestHeader('Content-Type', 'application/json');
    req.setRequestHeader('Authorization', 'Basic '+ btoa(user + ":" + password));
    req.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    req.onreadystatechange = () => {
        debugger;
        if (req.readyState === 4) {
            ///////////////// it comes here but req.status is 0
            if (req.status >= 200 && req.status < 400) {
                debugger;
                // JSON.parse(req.responseText) etc.
            } else {
                // Handle error case
            }
        }
    };
    req.send(body);
}

这是我在网络标签中看到的:

enter image description here

1 个答案:

答案 0 :(得分:0)

您遇到了CORS问题。这就是为什么它与Postman一起工​​作,它跳过那个检查(OPTIONS调用相同的请求而不是GET)并且您的React App(或任何Javascript Ajax调用)失败,因为您的浏览器在启动之前检查它请求..

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

这篇文章展示了如何处理CORS https://www.eriwen.com/javascript/how-to-cors/