Home > Back-end >  Recieving a 422 http error when trying to login using axios with react
Recieving a 422 http error when trying to login using axios with react

Time:12-24

Hello I am trying to post login details to my back end using axios, when I try it on Postman it works fine but when I do it through my front end I receive error 422

I am using fast API as my backend, a colleague is building it not me

I am using React as my frontend

here is my code:

import React, { Component } from 'react';
import'./login.css';
import axios from 'axios';

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(e){
    this.setState({[e.target.name] : e.target.value})
  }
  handleSubmit(e){
    e.preventDefault();
    const data = { username: this.state.username,
      password: this.state.password};
      
    
    axios.post('https://fastapi-aadil.herokuapp.com/login,
        data, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
  ) 
  .then(res => {
    console.log(res);
    console.log(res.data)
  })
  .catch(err => {
    console.log(err.response);
  });
  }
  render()

the error I Receive

xhr.js:210 POST https://fastapi-aadil.herokuapp.com/login 422 (Unprocessable Entity)

I am not sure where I am doing it wrong I have tried and changed almost everything but it doesn't seem to work.

Thanks

CodePudding user response:

You cannot use application/x-www-form-urlencoded like this with axios. See below on how to use it with axios.


handleSubmit(e){
    e.preventDefault();
    const data = new URLSearchParams()
    params.append('username', this.state.username)
    params.append('password', this.state.password)
    
    axios.post(
        'https://fastapi-aadil.herokuapp.com/login',
        data, 
        { 
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }
   ) 
   .then(res => {
      console.log(res);
      console.log(res.data)
   })
      .catch(err => {
      console.log(err.response);
   });
}

CodePudding user response:

As @Tobi said in the previous answer that I can't use x-www-form-urlencoded I searched on axios docs on how to use it with react it turned out we must use qs to stringify the data when making a post request.

and here is my code it worked fine.

 handleSubmit(e){
    e.preventDefault();
    const values = {'username': this.state.username, 
    'password':this.state.password
  }
  const data = qs.stringify(values)
      
    
    axios.post('https://fastapi-aadil.herokuapp.com/login',
        data, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
  ) 
  .then(res => {
    console.log(res);
    console.log(res.data)
  })
  .catch(err => {
    console.log(err.response);
  });
  • Related