AXIOS SENDS 2 REQUESTS INSTEAD OF 1

Asked

Viewed 286 times

-1

Summary : When I Make Backend Requests with Postman all goes well, but when I make requests with Front-End Reactjs Axios 2 requests come to the API, 1 without Token and the other with Token.

I am in a project consisting of a Java API (JAX-RS - JERSEY2) that is consumed by a REACTJS application (Axios implementing Xmlhttprequest).

When the Front-End makes a Request for the API in certain End-Points it is necessary to use the Token in the Request Header.

Follow the API Filter code:

@Provider()
@Priority(Priorities.AUTHENTICATION)
public class Authentication implements ContainerRequestFilter {

    @Context
    private UriInfo uriInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        JWTController jwt_controller = new JWTController();
        String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
        System.out.println(authorizationHeader == null);
    }
}

Requests made with POSTMAN returns :

> false

Requests made with AXIOS returns :

> true
> false

Follows Javascript code that makes the requests:

Archive that stores Axios services/api Instances:

import Axios from 'axios';

export const api = Axios.create(//Instacia para requisições sem Token
    {
        baseURL:"http://localhost:8080/beta_projects"
    }
);
export const api_with_token = Axios.create(//Instacia para requisições com Token
    {
        baseURL:"http://localhost:8080/beta_projects"      
    }
);

pages/home.js file:

try {
            let token = localStorage.getItem("token");
            let id_user = getIdUser(token);
            let URL = `user/${id_user}/activities`;
            api_with_token.defaults.headers.common['Authorization'] = `Bearer ${token}`;
            let response = await api_with_token.get(URL);
            this.setState({ activities: response.data });
            console.log(response.data);
            return response;
        } catch (err) {
            console.log(err.response);
            return err;
        }

I don’t understand why the two requests.

[RESOLUTION] Open the authentication filter for OPTIONS type requests as follows

if (isPublic() || requestContext.getMethod().equals("OPTIONS")) {
            return;

}

  • take a look at the browser’s network tab and see the requests, I think it’s very likely that the first request is a call of options

  • Yes, I’m doing a GET on the API, and the first one is the OPTIONS type. Apparently it’s there bringing information from the API.. But how could I filter it?

  • The Source I’m looking for is of the GET type, but it sends this PREFLIGHT Request of the OPTIONS type and it returns with the 401 status.

  • there is no way to escape much of this since whenever a request is sent "not simple" this options will be sent before, what you can do maybe would be to release the request options in the Cors config of your backend

1 answer

0

The false occurs probably because the first request is options and then there is an update of the state of the component, making it render again, then occurs the second call that returns true.

Try to do it the traditional way using then, catch so you can get the answer from the server and if it is successful you already return true and if error occurs return false, follow:

   try {
        let token = localStorage.getItem("token");
        let id_user = getIdUser(token);
        let URL = `user/${id_user}/activities`;
        api_with_token.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        await api_with_token.get(URL).then((response) => {
        this.setState({ activities: response.data });
        console.log(response.data);
        return true;
        }).catch((err) => {console.log('Erro: ', err); return false;});
    } catch (err) {
        console.log(err.response);
        return err;
    }
  • Good night Lucas! Vi in the browser’s network tab and it makes two calls 1 Options and another with the verb I chose (POST, GET, PUT, DELETE, etc).. The "problem" was in the Back-End CORS because it was not authorizing requests without an Authorization header and in the case of the Options verb it does not carry the Token together. The solution was to release the CORS filter when requests are of the OPTIONS type. Thank you very much for the reply!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.