I set up an API in Java. But now I'm developping a client in ReactJS. The authentication uses a JWT Token. With Postman, when I send a POST request to the authentication URL, it returns me a JWT token like this :
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZHVzZXIiOjEsImlzcyI6ImF1dGgwIn0.0BXAQl-yMIDeAU6Emppo6LBIm1RAdLa9vDWbQkdLs1o
That's exactly what I want. But I don't know how to retrieve a string after a fetch call in ReactJS.
I tried to use the promises and wrote this :
.then((data) => {
data.text().then((token) => {
alert(token)
})
})
But it returns me nothing, I have an alert with no text. How to get String from the Object Response returned by the fetch ?
I set up an API in Java. But now I'm developping a client in ReactJS. The authentication uses a JWT Token. With Postman, when I send a POST request to the authentication URL, it returns me a JWT token like this :
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZHVzZXIiOjEsImlzcyI6ImF1dGgwIn0.0BXAQl-yMIDeAU6Emppo6LBIm1RAdLa9vDWbQkdLs1o
That's exactly what I want. But I don't know how to retrieve a string after a fetch call in ReactJS.
I tried to use the promises and wrote this :
.then((data) => {
data.text().then((token) => {
alert(token)
})
})
But it returns me nothing, I have an alert with no text. How to get String from the Object Response returned by the fetch ?
data
?
– Andy
Commented
Dec 23, 2017 at 19:12
Response { type: "cors", url: "http://localhost:8080/projet_p52/Signin/apiSignin/signin", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, bodyUsed: false }
– Dylan M.
Commented
Dec 23, 2017 at 19:15
data.headers.Authorization
or some other header field. In your then()
method callback add a console.log(data.headers);
and look at the value.
– Kyle Richardson
Commented
Dec 23, 2017 at 19:24
Maybe you back end server return Content-Type=application/json
? Instead text()
method try using json()
.
Try this:
fetch('/next/page')
.then(function(response) {
return response.text();
})
.then(function(text) {
// <!DOCTYPE ....
console.log(text);
});
I was facing the same issue and was able to get the token with this:
.then(res => res.json()).then(res => {
let token = res.token;
console.log("token: ", token);
});
Source: https://developer.mozilla/en-US/docs/Web/API/Body
The text() method on that response object is what you are looking for.
Using await
syntax I think is a bit simpler than using then()
With await, this
in this.setState()
is scoped as expected.
async getStrResponse() {
const response = await fetch('myController/GetStringTest');
const stringResponse = await response.text();
this.setState({ someStr: stringResponse, loading: false });
}