Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  192] [ 6]  / answers: 1 / hits: 15839  / 4 Years ago, thu, july 9, 2020, 12:00:00

newbie here :)


I am trying to learn about JWT Authentication following a tutorial with Django back end and React. https://hackernoon.com/110percent-complete-jwt-authentication-with-django-and-react-2020-iejq34ta .


I solve many unexpected errors on this tutorial before with online searching, but now i can't find a solution.


I am on first steps to use Axios for requests and tokens, from tutorial :


" We want to use Axios for: POSTing to /api/user/create/ to create a userPOSTing to /api/token/obtain/ to login a user and obtain a JWT token pairPOSTing to /api/token/refresh/ to refresh the JWT token pairGETting from the protected /api/hello/ to see what the backend secretly has to say "


The expected behavior based on the tutorial is on (Image 1) :


The expected behavior : Image 1


But after npm run build command python manage.py runserver command, i am trying to Log In in the system and i got this error on firefox console (Image 2)


Error on firefox console : Image 2


Also, on Django console i got "OPTIONS /api/token/obtain/ HTTP/1.1" 200 372 instead of "POST /api/token/obtain/ HTTP/1.1" 200 491.


The files i used for this section of tutorial is :


// djsr/frontend/src/axiosApi.js

import axios from 'axios'

const axiosInstance = axios.create({
baseURL: 'http://127.0.0.1:8000/api/',
timeout: 5000,
headers: {
'Access-Control-Allow-Origin': '*'
'Authorization': "JWT " + localStorage.getItem('access_token'),
'Content-Type': 'application/json',
'accept': 'application/json'
}
});

export default axiosInstance;

Note : I found online that I should put 'Access-Control-Allow-Origin': '*' on headers in djsr/frontend/src/axiosApi.js but nothing happens with this.


and the :


// djsr/frontend/src/components/login.js

import React, { Component } from "react";
import axiosInstance from "../axiosApi";

class Login extends Component {
constructor(props) {
super(props);
this.state = {username: "", password: ""};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
this.setState({[event.target.name]: event.target.value});
}

handleSubmit(event) {
event.preventDefault();
try {

const response = axiosInstance.post('/token/obtain/', {
username: this.state.username,
password: this.state.password
});
axiosInstance.defaults.headers['Authorization'] = "JWT " + response.data.access;
localStorage.setItem('access_token', response.data.access);
localStorage.setItem('refresh_token', response.data.refresh);
return data;
} catch (error) {
throw error;
}
}

render() {
return (
<div>
Login
<form onSubmit={this.handleSubmit}>
<label>
Username:
<input name="username" type="text" value={this.state.username} onChange={this.handleChange}/>
</label>
<label>
Password:
<input name="password" type="password" value={this.state.password} onChange={this.handleChange}/>
</label>
<input type="submit" value="Submit"/>
</form>
</div>
)
}
}
export default Login;

P.S : I really hope for a solution, to finish this tutorial, to be happy :)
Thank you all for your time and for help!!


More From » reactjs

 Answers
202

OK guys I figured it out.
Help from this post : THE SOLUTION


I need to enable corsheaders in Django.


First off all, I install corsheaders with pip install django-cors-headers, and add in settings.py :


In middleware :


MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsMiddleware',
]

In installed apps :


INSTALLED_APPS = [
'corsheaders',
]

And include this setting :


CORS_ORIGIN_ALLOW_ALL = True

And remove from axiosApi.js the :


{headers: {"Access-Control-Allow-Origin": "*"}

Also, https://stackoverflow.com/a/62824251/10182785 this answer was helpful for me.


[#50818] Friday, June 26, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
khalidkendelld

Total Points: 55
Total Questions: 99
Total Answers: 77

Location: South Korea
Member since Tue, Feb 22, 2022
2 Years ago
;