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); }); },
额外提示
- 后端代码返回的
acess_token存在拼写错误,正确应为access_token,建议修正后端返回字段,避免前端解构出错。 - 若不想使用
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
相关产品推荐
相关产品推荐

