繁体   English   中英

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));
});

当我运行此代码时,我点击调试器并且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)出现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)在catch块中。 但是,在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的帮助: 为Web Api 2和OWIN令牌认证启用CORS

它应该通过添加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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM