Next.js集成Passport.JS时axios POST /api/signin返回400 Bad Request问题
错误原因
- 核心是
axios.post的传参格式使用错误:axios.post方法的参数顺序为axios.post(请求URL, 请求体数据, 配置对象),你当前把params、withCredentials、headers这些本属于第三个参数的配置项,全部放到了第二个请求体参数里,导致后端接口收到的请求体结构不符合预期,无法正确解析出email和password字段,因此返回400错误。 - 从你返回的config字段可以验证这个问题:实际发送的请求体是
{"params":{"email":"xxxxxx@gmail.com","password":"Aug8162016!"},...},而非后端预期的{"email":"xxxxxx@gmail.com","password":"Aug8162016!"}。
修复方案
把请求参数拆分到正确的位置即可,修改后的代码如下:
import axios from 'axios'; export default function loginSubmit( email, password, ) { // 直接作为请求体传递 const loginData = { email, password, }; axios .post(`/api/signin`, loginData, { withCredentials: true, headers: { 'Content-Type': 'application/json' } }) .then(response => { // 处理成功逻辑 }) .catch((error) => { if (error.response) { console.log("error.response ", error.response); } else if (error.request) { console.log("error.request ", error.request); } else if (error.message) { // 其他错误场景处理逻辑 } }) }
获取更详细错误信息的方法
- 后端侧可以在next-connect的路由处理逻辑中,增加参数校验失败的返回信息,比如使用
next-connect的onError全局错误处理钩子,把具体的校验错误原因(比如缺少email字段、密码格式错误等)序列化后返回给前端,而不是直接返回默认的Bad Request。 - 前端侧可以在catch块中打印完整的
error对象,也可以使用浏览器开发者工具的网络面板,查看本次请求的完整请求体、请求头、响应详情,确认请求参数是否符合预期。
内容的提问来源于stack exchange,提问作者Antonio Pavicevac-Ortiz
相关产品推荐
相关产品推荐

