im trying to handle login with JWT auth and axios in my reactjs app; but everytime i send my data into the backend i get "'data' is not defined no-undef" error...
this is my handle submit code in Login.js:
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'] = "Bearer " + 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 (...
and this in my axiosInstance file :
const axiosInstance = axios.create({
baseURL: 'http://127.0.0.1:8000/',
timeout: 5000,
headers: {
'Authorization': "Bearer " + localStorage.getItem('access_token'),
'Content-Type': 'application/json',
'accept': 'application/json'
}
});
how can in handle this error "'data' is not defined no-undef" ????
I think you are missing await
... await axios.post(...
Or you can handle like this
axios.post(...).then(response => { //response.data.access can be found here }
But of course you better check documentation of axios and check what a Promise is