2

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',
    ],
  ...
}
2
  • Have you tried response.data.token? Or log the whole response and check what you get, to verify that the token is present Commented Apr 18, 2019 at 19:35
  • Response {type: "cors", url: "127.0.0.1:8000/api/get-token", redirected: false, status: 200, ok: true, …} body: ReadableStream bodyUsed: false headers: Headers proto: Headers ok: true redirected: false status: 200 statusText: "OK" type: "cors" url: "127.0.0.1:8000/api/get-token" proto: Response This is the response I am getting. I don't think it has the token. when I try response.data.token App.js:20 Uncaught (in promise) TypeError: Cannot read property 'token' of undefined at App.js:20 I get this Commented Apr 18, 2019 at 20:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So now that I am getting the token can I use the same format to hit the api endpoint where I am trying to get the serialized data from? ``` fetch('127.0.0.1:8000/api/testbuildingtype', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authentication': 'Token ' + token } }).then(function(response) { return response.json(); }).then(function(data){ console.log(data); }) ```
@DaminiGanesh yes, that should work. You should always read the response stream using either .text() or .json() to access the data using fetch.
But I get this error now Access to fetch at '127.0.0.1:8000/api/testbuildingtype' from origin 'localhost:3000' has been blocked by CORS policy: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response. localhost/:1 Uncaught (in promise) TypeError: Failed to fetch I tried both .text() and .json()
@DaminiGanesh that's a whole different issue. You should check out django-rest-framework.org/topics/ajax-csrf-cors

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.