Search code examples
javareactjsheaderauthorizationtoken

React app not sending headers to java server


I searched a lot on the Internet, but I didn't find anything helpful for my problem. I have a java server and a react client. My server is using jwt for authentication and returns a token to my client.

When I try to send data with a post method, my client does not send the headers, so my server returns an "Unauthorized" message. I tried to send the same request from Postman and ARC(Advanced Rest Client) and it works.

Here is my client code:

fetch(url, {
            method: 'POST',
            crossDomain: true,
            mode: 'no-cors',
            body: JSON.stringify(data),
            headers: {
                'Authorization': 'Bearer ' + 'token generated from fiddler after running auth',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(responseJson => {
                console.log(responseJson);
            });

I tried using axios too and I have the same problem. Also my server has @CrossOrigin(origins = {"*"}) annotation in all controller classes.

I don't know if my problem is with the client or with the server and why is working using Postman and ARC.


Solution

  • You are using mode: no-cors which basically strips out all headers which are not simple headers: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode

    You should enable CORS and allow your domain on the server.