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.

sander
  • 1,426
  • 4
  • 19
  • 46
  • I searched some more and I think it might have something to do with this post: https://stackoverflow.com/a/44816592/8608962 – sander Jan 05 '18 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](https://developer.mozilla.org/en-US/docs/Web/API/Response) object – Jaromanda X Jan 05 '18 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? – sander Jan 05 '18 at 23:05
  • 1
    well, you need to **specify** which headers to expose - then, the `jwt` header is accessed using `data.headers.get('jwt')` – Jaromanda X Jan 05 '18 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 – Jaromanda X Jan 06 '18 at 00:02

1 Answers1

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);
});
Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141