1

I'm using React and using fetch to send a request to the server:

fetch("http://localhost:8001/api/login", {
    method: 'post',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: 'username=' + this.state.username + '&password=' + this.state.password
})
.then(function (response) {
    console.log('Request succeeded with JSON response', data);
    console.log(data.headers.toString())
})
.catch(function (error) {
    console.log('Request failed', error);
});

This is chrome inspect, it shows that I get JWT token from server My question is how do I access it in my code? I actually need to save it to a variable, there's really no way to do

data.headers.jwt

I'm sorry if this makes no sense, I can clarify if you need.

5
  • I searched some more and I think it might have something to do with this post: stackoverflow.com/a/44816592/8608962 Commented Jan 5, 2018 at 22:58
  • 2
    yes, server needs to send appropriate access-control-expose-headers to expose them. Note: where you say Request succeeded with JSON response that's not a JSON response, it's a Response object Commented Jan 5, 2018 at 23:02
  • I added header('access-control-expose-headers'); to the beginning of the server file. How would I access the headers in ReactJS? Commented Jan 5, 2018 at 23:05
  • 1
    well, you need to specify which headers to expose - then, the jwt header is accessed using data.headers.get('jwt') Commented Jan 5, 2018 at 23:07
  • 2
    to be honest, unless there's a really good reason not to, I'd put the jwt in the response body, not a response header - but, as your code as posted doesn't ever access the response body, it's hard to say if adding the jwt to the response body is correct for your case or not Commented Jan 6, 2018 at 0:02

1 Answer 1

5

Here's the code you need. As a bonus, I have added on some code to show you how to use the response data.

fetch("http://localhost:8001/api/login", {
    method: 'post',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: 'username=' + this.state.username + '&password=' + this.state.password
})
.then(function (response) {
    console.log('My JWT:', response.headers.get('jwt'));
    return response.json();
})
.then(function (data) {
    // Do something with JSON data.
})
.catch(function (error) {
    console.log('Request failed', error);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.