Reputation: 308
I am linking django to react.
I am trying to get the token from a Django-rest-framework endpoint http://127.0.0.1:8000/api/get-token which is using a tokenAuthentication, from react app.js . I have set up corsheaders and restframework all that. when I hit the endpoint through the command line with a token it works. Now I need the token in my react app.js. I get a response with status 200 but I can't find the token. As I am new to react I am not sure if I am missing something. //App.js
componentDidMount() {
try {
const data = {username: 'user', password: 'password'};
fetch('http://127.0.0.1:8000/api/get-token/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then(function(response) {
console.log(response.token);
})
} catch (e) {
console.log(e);
}
}
Let me know if you need more info
I have tried both TokenAuthentication and BasicAuthentication in my settings.py
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
...
}
Upvotes: 2
Views: 1098
Reputation: 550
When using fetch, you first have to read the response stream using .response.json()
.
This is your code example with an extra then
after the fetch, to return a new promise containing your data (parsed with JSON):
componentDidMount() {
try {
const data = {username: 'user', password: 'password'};
fetch('http://127.0.0.1:8000/api/get-token/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data.token);
})
} catch (e) {
console.log(e);
}
}
Note: if the data you receive from the server is not JSON, you should use response.text()
to just parse the response as a string.
Upvotes: 2