【发布时间】: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