You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue调用FastAPI OAuth2登录接口时出现422 Unprocessable Entity错误

解决FastAPI OAuth2PasswordRequestForm与Vue请求的422错误

你的问题出在Vue的axios请求写法上——你把FormData对象包裹在了普通JavaScript对象里发送,导致后端无法解析出符合OAuth2PasswordRequestForm要求的表单数据格式。

错误原因分析

OAuth2PasswordRequestForm要求前端发送表单格式的请求(application/x-www-form-urlencoded或multipart/form-data),但你当前的代码:

axios.post('http://localhost:5001/auth/token', {
    formData,
})

实际发送的是JSON格式的请求体,结构为{"formData": [FormData实例]},完全不符合后端的解析规则,因此返回422错误。

修正后的Vue代码

直接将FormData实例作为axios.post的第二个参数传入即可:

login(username, password) {
    // Function to make a login request
    username = this.InputUsername
    password = this.InputPassword
    const formData = new FormData();
    
    formData.append('username', username);
    formData.append('password', password);

    console.log(formData)
    axios.post('http://localhost:5001/auth/token', formData)
        .then((response) => {
            // 注意:后端返回字段拼写为acess_token(少了字母c),需对应解构
            const { acess_token } = response.data;
            this.setAuthToken(acess_token);
            alert("Login")
        })
        .catch((error) => {
            console.error(error);
        });
},

额外提示

  1. 后端代码返回的acess_token存在拼写错误,正确应为access_token,建议修正后端返回字段,避免前端解构出错。
  2. 若不想使用FormData,也可发送application/x-www-form-urlencoded格式数据,借助qs.stringify处理:
import qs from 'qs';

// ...
axios.post('http://localhost:5001/auth/token', qs.stringify({
    username: this.InputUsername,
    password: this.InputPassword
}))

内容的提问来源于stack exchange,提问作者WIsh Suharitdamrong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:27:18