Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: enter image description here

like image 887
Alan Schapira Avatar asked Dec 26 '17 11:12

Alan Schapira


People also ask

Can I use Axios in React?

It allows you to fetch data and make HTTP requests. This one is the common method to communicate with the database in React. In React there is another method to communicate with the backend server and that requires the installation of a popular library Axios.

Which is better fetch or Axios?

Axios allows cancelling request and request timeout. Fetch does not. Axios has the ability to intercept HTTP requests. Fetch, by default, doesn't provide a way to intercept requests.

What is the purpose of Axios?

Axios is a promised-based HTTP client for JavaScript. It has the ability to make HTTP requests from the browser and handle the transformation of request and response data.


2 Answers

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

like image 78
Alan Schapira Avatar answered Sep 28 '22 02:09

Alan Schapira


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)
like image 45
Dyo Avatar answered Sep 28 '22 03:09

Dyo