POST 400 错误请求 React 身份验证

时间:2021-01-07 15:12:25

标签: reactjs axios

知道是什么导致了该错误?我正在尝试使用此 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

2 个答案:

答案 0 :(得分:2)

如果你控制台输入对你有好处,因为 400 bad request 与输入和输出错误(错误的输入体)有关。 如果您能够控制台并且值正确打印为 json 对象,那么如果他们接受作为对象(输入中的 JSON 数据),请联系后端人员。 尝试使用此示例:

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));

输出:[错误:请求失败,状态码为 401](表示可以发送成功请求)

答案 1 :(得分:2)

您需要在帖子请求中添加标头。

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

与邮递员一起尝试过,它奏效了。