繁体   English   中英

尝试使用带有反应的 axios 登录时收到 422 http 错误

[英]Recieving a 422 http error when trying to login using axios with react

您好我正在尝试使用 axios 将登录详细信息发布到我的后端,当我在 Postman 上尝试它时它工作正常但是当我通过我的前端执行它时我收到错误 422

我正在使用快速 API 作为我的后端,一位同事正在构建它而不是我

我使用 React 作为我的前端

这是我的代码:

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

我收到的错误

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

我不确定我在哪里做错了我已经尝试并改变了几乎所有东西,但它似乎不起作用。

谢谢

您不能像这样将application/x-www-form-urlencoded与 axios 一起使用。 请参阅下文,了解如何将其与 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);
  });
}

正如@Tobi 在上一个答案中所说,我不能使用x-www-form-urlencoded我在 axios 文档上搜索了如何使用它来做出反应,结果发现我们必须在发出发布请求时使用 qs 对数据进行字符串化。

这是我的代码,它运行良好。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM