简体   繁体   English

React Axios - C#WebAPI请求令牌失败,没有服务器错误

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

I have the following code: 我有以下代码:

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

When I run this code, I hit the debugger and the error object has 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) in the catch block. 当我运行此代码时,我点击调试器并且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块中。 However, in the network tab in Chrome, the Status code is 200, but when I click on the response/preview tabs of this request there is no data. 但是,在Chrome的网络标签中,状态代码为200,但是当我点击此请求的响应/预览标签时,没有数据。 If I click on continue, I actually get the token and other data in the response/preview tab as expected, but at this point it has already reached the catch block so will not hit the then block. 如果我点击继续,我实际上会按预期在响应/预览选项卡中获取令牌和其他数据,但此时它已经到达了catch块,因此不会点击then块。

I have even debugged the back-end and it doesn't send back an error, so I assume this is a front end error. 我甚至调试了后端,它没有发回错误,所以我认为这是一个前端错误。 Does anyone know what is causing this? 有谁知道是什么原因造成的?

Edit: 编辑:

Just to add more details, if I change the request to work with fetch instead of axios, I am getting a different error TypeError: Failed to fetch . 只是为了添加更多细节,如果我将请求更改为使用fetch而不是axios,我会收到一个不同的错误TypeError: Failed to fetch The code used for the call is: 用于呼叫的代码是:

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

Also, this is an example of the postman request working correctly: 此外,这是邮递员请求正常工作的示例: 在此输入图像描述

Finally found my answer. 终于找到了答案。 It turns out I had not enabled CORS in my WebAPI back-end for the /token endpoint. 事实证明,我没有在我的WebAPI后端为/token端点启用CORS。 The way I was able to resolve this was by enabling CORS in the MyProject\\Providers\\ApplicationOAuthProvider.cs by adding the line context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); 我能够解决这个问题的方法是在MyProject\\Providers\\ApplicationOAuthProvider.cs启用CORS,方法是添加行context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); to the top of the method named GrantResourceOwnerCredentials . 到名为GrantResourceOwnerCredentials的方法的顶部。 I do think there are better ways to enable CORS for the entire project which I will look into next! 我认为有更好的方法为整个项目启用CORS,我将在下面介绍!

Got some help from here about how to enable the CORS: Enable CORS for Web Api 2 and OWIN token authentication 从这里获得了一些关于如何启用CORS的帮助: 为Web Api 2和OWIN令牌认证启用CORS

It should work with fetch by adding content-type : 它应该通过添加content-type来获取fetch:

fetch(`${ROOT_URL}token`, {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    body: data
})

You can try this in axios too but it seems related to an axios bug , you can give a try by adding the params property : 您也可以在axios中尝试这个,但它似乎与axios bug有关 ,您可以尝试添加params属性:

axios.post(`${ROOT_URL}token`, data, params: data)

暂无
暂无

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

相关问题 C#调用aspnet webapi令牌终结点在我的本地主机上完美运行,但在服务器上给出错误 - C# calling aspnet webapi token endpoint works perfectly on my localhost but givens error on server 本地主机上的 React Native 和 C# WebAPI 之间的获取命令返回网络请求失败错误 - Fetch Command Between React Native and C# WebAPI on Localhost Returns Network Request Failed error C# webapi Cors 服务器中的选项请求返回错误 404 未找到 - C# webapi Cors Option request in server returns error 404 not found 使用 PostMan 测试的 C# webapi 身份验证令牌错误 - C# webapi authentication token ERROR tested with PostMan 如何禁用从 C# WebApi 到 MarkLogic 服务器的预检请求 - How to disable preflight request to MarkLogic server from C# WebApi c# 获取 oauth2 令牌但得到错误(远程服务器返回 400 Bad Request) - c# to get oauth2 token but get error (Remote server returns 400 Bad Request) c# WebAPI API Issue - Swagger - Angular Axios - c# WebAPI API Issue - Swagger - Angular Axios C#Webapi帮助页面请求模型自定义 - C# Webapi HelpPage Request Model Customization C# NetCore WebAPI 集成测试:HttpClient 使用 HTTPS 进行 GET 请求,但随后仅使用 HTTP 进行 POST 请求,并失败并出现 Forbidden - C# NetCore WebAPI integration testing: HttpClient uses HTTPS for GET request, but then uses only HTTP for the POST request, and fails with Forbidden 从React将Json发布到C#WebApi - Posting Json to C# WebApi from React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM