0

I'm building a simple API, but right now I'm having some issues with the back-end. I always used the Django-rest-framework serializers, but now I'm trying to code a function-based view. My back-end server uses knox token authentication as a default, I have this set up in the Django settings (below)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':
    ('knox.auth.TokenAuthentication', )
}

So the thing is that when the POST request is sent from the postman, the server identifies the user which calls the request, but when the request is sent from React JS the server couldn't find the user.

This is my views.py function-based view:

@csrf_exempt
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def hello_world(request):
    print(request.data)
    print(request.headers)
    print('user', request.user.username)

This is what I get when sending the request from POSTMAN -

{'report': 'testas'}
{'Content-Length': '28', 'Content-Type': 'application/json', 'Authorization': 'Token 024f51b3f210082302ceb1fff29eff3fcefd50437c6909ca7d6647a1ce1d66bb', 'User-Agent': 'PostmanRuntime/7.26.8', 'Accept': '*/*', 'Postman-Token': '5e9be4f1-cbf5-4f8f-bf7c-f44761c30798', 'Host': '192.168.0.30:8000', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive'}
user 3nematix

And this comes from React JS :

{'headers': {'Content-Type': 'application/json', 'Authorization': 'Token d8bce38c58d07ade11446147cab60ac7795813232cc44d93e9d0da46bd16384e'}}
{'Content-Length': '136', 'Content-Type': 'application/json;charset=UTF-8', 'Host': '192.168.0.30:8000', 'Connection': 'keep-alive', 'Accept': 'application/json, text/plain, */*', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'Origin': 'http://192.168.0.30:8000', 'Referer': 'http://192.168.0.30:8000/reports/view', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9'}
user

How can I fix the issue? I have other serializers that identify React JS requests, but when I tried the function-based view, this is the first one that doesn't.

React JS Axios API call:

import axios from 'axios';
import tokenConfig from './auth';

// Like Report
export const likePostas = (report_public_id) => (dispatch, getState) => {
  axios
    .post(`/api/report/like?report=${report_public_id}`, tokenConfig(getState))
    .then((res) => {
      console.log(res.data)
    })
    .catch(err => {
      console.log(err.response.data)
    });
};

The tokenConfig function:

// Setup config with token - helper function
export const tokenConfig = (getState) => {
  // Get token from state
  const token = getState().auth.token;

  // Headers
  const config = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // If token, add to headers config
  if (token) {
    config.headers['Authorization'] = `Token ${token}`;
  }

  return config;
};

export default tokenConfig;
pplonski
  • 5,023
  • 1
  • 30
  • 34
DzITC
  • 869
  • 1
  • 9
  • 23

2 Answers2

1

try something like that if you don't want to pass the data

import axios from 'axios';
import tokenConfig from './auth';

// Like Report
export const likePostas = (report_public_id) => (dispatch, getState) => {
  axios
    .post(`/api/report/like?report=${report_public_id}`, {}, tokenConfig(getState))
    .then((res) => {
      console.log(res.data)
    })
    .catch(err => {
      console.log(err.response.data)
    });
};
Nisharg Shah
  • 16,638
  • 10
  • 62
  • 73
0

I will describe my approach for Django+React app. When I get the token from the server I set it in axios defaults, so I don't need to remember to add it:

export const setAxiosAuthToken = token => {
  if (typeof token !== "undefined" && token) {
    // Apply for every request
    axios.defaults.headers.common["Authorization"] = "Token " + token;
  } else {
    // Delete auth header
    delete axios.defaults.headers.common["Authorization"];
  }
};

If you logout, then just call the above function with an empty string as a token.

I'm working on complete tutorial how to write SaaS application with Django+React from scratch. You can read the article about login feature in React to Django backend.

pplonski
  • 5,023
  • 1
  • 30
  • 34