简体   繁体   English

通过授权反应远程请求

[英]React remote request with authorization

I want to do a remote request using React JS. 我想使用React JS进行远程请求。 I try to do it as follows: 我尝试这样做,如下所示:

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

I get an error: 我收到一个错误: 在此处输入图片说明 在此处输入图片说明

If I do the same request with the same credentials with postman it works: 如果我使用邮递员以相同的凭证执行相同的请求,则它的工作原理是:

在此处输入图片说明

Any idea? 任何想法?

UPDATE 更新

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

This is what I see in network tab: 这是我在“网络”标签中看到的内容:

在此处输入图片说明

You are having CORS problems. 您遇到CORS问题。 This is why it's working with Postman, it skips that check (OPTIONS call to the same request instead the GET one) and your React App (or any Javascript Ajax call ) fails, because your browser is checking it before launch the request.. 这就是为什么它与Postman一起工​​作的原因,它跳过了该检查(对同一请求的OPTIONS调用而不是GET一个请求),并且您的React App(或任何Javascript Ajax调用)失败了,因为您的浏览器在启动请求之前对其进行了检查。

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

This post shows how to deal with CORS https://www.eriwen.com/javascript/how-to-cors/ 这篇文章显示了如何处理CORS https://www.eriwen.com/javascript/how-to-cors/

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

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