Axios基本授权不经过Reactjs
第一次问,所以我在这里。Axios基本授权不经过Reactjs
我正在尝试对我的团队所做的需要授权的stormpath应用程序进行GET调用。当使用邮差测试和一些配置后,一切都出来了200
Results of API call in Postman
使用curl工作
curl --verbose --user ID:SECRET -H "Accept: application/json" https://api.stormpath.com/v1/tenants/current
...
< HTTP/1.1 302
< Cache-Control: private, no-cache, no-store, max-age=0, no-transform
< Date: Tue, 10 Jan 2017 09:27:14 GMT
< Location: https://api.stormpath.com/v1/tenants/TENANTID
< Pragma: no-cache
< Stormpath-Request-Id: f8e4dee0-d716-11e6-9795-22000aa92aa2
< Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
< X-Frame-Options: SAMEORIGIN
< Content-Length: 0
< Connection: keep-alive
<
* Connection #0 to host api.stormpath.com left intact
但是,当我试图在React
拨打电话通过Axios
我得到一个401错误。
XMLHttpRequest cannot load https://api.stormpath.com/v1/tenants/current. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.
这是我用什么:
axios({
method: 'get',
url: "https://api.stormpath.com/v1/tenants/current",
auth:
{
username: 'api ID',
password: 'api Secret'
}
})
我不知道为什么,但根据我得到的回应它不提供用户名和密码。
code:401
developerMessage:"Authentication with a valid API Key is required."
message:"Authentication required."
moreInfo:"http://www.stormpath.com/docs/quickstart/connect"
requestId:"3686f590-d69e-11e6-9b8a-22000a8ce5d1"
status:401
它似乎有类似的问题之前曾被问过,但仍然没有对他们的回应。
Reactjs Axios/Spring boot security
Cannot Basic Auth from React App with Axios or SuperAgent
感谢的抽出时间来阅读。
好吧,所以我想不通为什么axios
验证呼叫不起作用,但我找到了一种方法来通过。我所做的是在express
内部而不是在React
内部进行auth API调用。
所以发生了什么是React
拨打我的服务器本地主机。
axios.get("/secret")
.then(
function(response)
{
console.log(response)
}
)
然后node/express服务器捕获它并运行我想要的API调用。我用request
和cors
app.use(cors());
...
app.get('/secret', function(req, res){
var queryUrl = "https://api.stormpath.com/v1/tenant/current;
request({url:queryUrl, auth: {
user: ID,
pass: SECRET
}}, function(err, response, body){
if(!err && response.statusCode == 200){
info = JSON.parse(body);
res.send(info);
}
else{
res.send(err)
}
})
})
而且它与所有我需要的stormpath API网址工作。
几个月前得到了同样的问题,最终得到了相同的解决方案。我认为它与前端的cors相关,因为您尝试为api命中其他域。
而且您将一些自定义身份验证数据添加到标头,因此您在拨打电话时可能需要使用'withCredentials:true'。然后它会导致预检选项呼叫问题。我认为它不应该在前端处理。希望这个帮助。
我试着添加withCredentials:true,它仍然没有工作 –
可能是无效的API密钥/秘密,如错误所述。 –
使用邮递员API密钥/秘密工作得很好。我甚至使用API密钥/秘密通过地址栏访问API,它仍然有效。 –