React Axios - C# WebAPI 请求令牌在没有服务器错误的情况下失败

React Axios - C# WebAPI request token fails without a server error

我有以下代码:

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中的network选项卡中,Status code是200,但是当我点击这个请求的response/preview选项卡时,却没有数据。如果我点击继续,我实际上按预期在 response/preview 选项卡中获得了令牌和其他数据,但此时它已经到达 catch 块,因此不会命中 then 块。

我什至调试了后端,它没有返回错误,所以我认为这是一个前端错误。有谁知道是什么原因造成的?

编辑:

只是为了添加更多细节,如果我将请求更改为使用 fetch 而不是 axios,我会收到不同的错误 TypeError: Failed to fetch。用于调用的代码是:

fetch(`${ROOT_URL}token`, {
    method: 'POST',
    body: data
})

此外,这是邮递员请求正常工作的示例:

它应该通过添加内容类型与 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)

终于找到我的答案了。原来我没有在我的 WebAPI 后端为 /token 端点启用 CORS。我能够解决这个问题的方法是在 MyProject\Providers\ApplicationOAuthProvider.cs 中启用 CORS,方法是将行 context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); 添加到名为 GrantResourceOwnerCredentials 的方法的顶部。我确实认为有更好的方法可以为整个项目启用 CORS,接下来我将研究它!

从这里得到了一些关于如何启用 CORS 的帮助: