【问题标题】:XMLHTTP Request bad respondheaderXMLHTTPRequest 错误响应标头
【发布时间】:2019-07-20 13:18:39
【问题描述】:

我正在尝试请求 api 来获取令牌。 令牌在 RespondHeader 中,但我的代码没有找到它。但是我用 curl 得到了它,所以可以肯定我错过了一些东西。 你能帮帮我吗?

这是卷曲: curl -i -X POST -H "Content-Type:application/json" http://127.0.0.1:8080/login -d '{"username":"poulet", "password":"poulet"}'

这就是我得到的

HTTP/1.1 200 
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJwb3VsZXQiLCJleHAiOjE1NTEzMDUxNDJ9.NTKyMKEKTnRDU-TzcG6WlNYVCjgQ91vBgK4SbTFECenRH_GCllxA-dPogx3RQ0XH0eCwH7LpCU8Ttyxb2idl_Q
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 0
Date: Tue, 26 Feb 2019 22:05:42 GMT

现在这是我的 Javascript 代码

const req = new XMLHttpRequest();
req.open('POST', 'http://127.0.0.1:8080/login', true);
req.setRequestHeader("Content-Type", "application/json");
req.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.getAllResponseHeaders());
        console.log(this.getResponseHeader("Authorization"));
    }
};
console.log(req);
req.send(JSON.stringify({username : "poulet", password : "poulet"}));

这就是我得到的

cache-control: no-cache, no-store, max-age=0, must-revalidate expires: 0 pragma: no-cache

提前谢谢你。

【问题讨论】:

  • 在您的回调函数中添加console.log(this.readyState, this.status); 以验证它已被调用。
  • 你在哪里运行这个;节点还是浏览器?如果是浏览器,页面的 URL 是什么?如果不在http://127.0.0.1:8080 上,您的 API 是否支持 CORS?是否报告了任何错误?
  • 我在浏览器中运行应用,url是127.0.0.1:8081,不知道api是否支持CORS:/
  • 好的问题解决了,是服务中的CORS问题。

标签: javascript api curl request


【解决方案1】:

所以如果人们有同样的问题。它是服务器,它没有跨域,因此缺少一些标头。

我通过添加解决它

访问控制允许来源:*

谢谢

【讨论】:

    【解决方案2】:

    尝试替换这个

    console.log(this.getResponseHeader("Authorization"));

    带有请求

    console.log(req.getResponseHeader("Authorization"));

    【讨论】:

    • 同样的事情,结果为空
    猜你喜欢
    • 2020-09-25
    • 2016-05-17
    • 2014-03-10
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多