我有以下代码:
var qs = require('qs');
const ROOT_URL = 'http://localhost:56765/';
const data = qs.stringify({ username, password, grant_type: 'password' });
axios.post(`${ROOT_URL}token`, data)
.then(response => {
debugger;
dispatch(authUser());
localStorage.setItem('token', response.data.token);
})
.catch((error) => {
debugger;
dispatch(authError(error.response));
});
当我运行此代码时,我点击了调试器,错误对象在catch块中有Error: Network Error at createError (http://localhost:3000/static/js/bundle.js:2188:15) at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:1724:14)
。但是,在Chrome的网络标签中,状态代码为200,但是当我点击此请求的响应/预览标签时,没有数据。如果我点击继续,我实际上会按预期在响应/预览选项卡中获取令牌和其他数据,但此时它已经到达了catch块,因此不会点击then块。
我甚至调试了后端,它没有发回错误,所以我认为这是一个前端错误。有谁知道是什么原因造成的?
编辑:
只是为了添加更多细节,如果我更改请求使用fetch而不是axios,我会得到一个不同的错误TypeError: Failed to fetch
。用于呼叫的代码是:
fetch(`${ROOT_URL}token`, {
method: 'POST',
body: data
})
终于找到了答案。事实证明,我没有在我的WebAPI后端为/token
端点启用CORS。我能够解决这个问题的方法是在MyProject\Providers\ApplicationOAuthProvider.cs
中启用CORS,方法是将context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
行添加到名为GrantResourceOwnerCredentials
的方法的顶部。我认为有更好的方法为整个项目启用CORS,我将在下面介绍!
从这里得到一些关于如何启用CORS的帮助:Enable CORS for Web Api 2 and OWIN token authentication
它应该通过添加content-type来获取fetch:
fetch(`${ROOT_URL}token`, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
body: data
})
您也可以在axios中尝试这个,但它似乎与axios bug相关,您可以尝试添加params
属性:
axios.post(`${ROOT_URL}token`, data, params: data)