jenlee123
jenlee123

Reputation: 153

POST 400 bad request React authentication

Any idea what may be causing that error? I am trying to authenticate the login with this API https://app.swaggerhub.com/apis/warp/etn-device-checker-test/1.0#/default/post_login

import React from 'react'
import axios from 'axios';
import { useState } from 'react';
function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const onSubmit = (e) => {
    e.preventDefault();
    const getIn = {
      "login":email,
      "password":password,
    };
          
    axios
      .post('https://js-test-api.etnetera.cz/api/v1/login', getIn)
      .then((res) => {
        console.log(res.data);                 
      })
      .catch((error) => console.log(error));
  };
  return (
    <div>
      <form >
        <label>email</label>
        <input value={email} onChange={(e) => setEmail(e.target.value)} type="text"/>
        <label>password</label>
        <input type="text" value={password} onChange={(e) => setPassword(e.target.value)}/>
        <button onClick={onSubmit}>login</button>
      </form>
    </div>
  )
}
        
export default Login

Upvotes: 1

Views: 2830

Answers (2)

Motiur Rehman
Motiur Rehman

Reputation: 36

It will be good for you if you console the input, because 400 bad request is related to input and out error (wrong input body). And if you are able to console and value is printing correctly as json object, then please contact backend person if they are accepting as an object (JSON data in input. try with this Sample:

axios.post('https://js-test-api.etnetera.cz/api/v1/login', getIn, {
        headers: {
            'Content-Type': 'application/json',
        }
    }).then((res) => {
        console.log(res.data);

    }).catch((error) => console.log(error));

output:[Error: Request failed with status code 401] (means it is able to send success request)

Upvotes: 2

ahmetkilinc
ahmetkilinc

Reputation: 684

You need to add headers to your post request.

axios.post(url, {
    //...data
}, {
    headers: {
       'content-type': 'application/json', 
   }
})

tried with postman and it worked.

Upvotes: 2

Related Questions