简体   繁体   中英

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. 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. 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.

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 . 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. 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[] { "*" }); to the top of the method named GrantResourceOwnerCredentials . I do think there are better ways to enable CORS for the entire project which I will look into next!

Got some help from here about how to enable the CORS: Enable CORS for Web Api 2 and OWIN token authentication

It should work with fetch by adding content-type :

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.post(`${ROOT_URL}token`, data, params: data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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