使用 Passport.JS 和 Next.JS 的 axios POST 到 /api/signin 的 400 错误请求

400 Bad request with axios POST to /api/signin using Passport.JS and Next.JS

我正在关注 example 回购 Next.js 提供实施 Passport.JS 和下一个连接。

我有一个表单提交处理程序,它在验证后发送 电子邮件 密码

我正在使用 axios:

import axios from 'axios';

export default function loginSubmit(
  email,
  password,
) {
  const loginData = {
    email,
    password,
  };
  axios
    .post(`/api/signin`, {
      params: 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) {
        // do something other than the other two
      }
}

我做了研究,400 Bad request 表示错误出在客户端。

一些想法是检查 URL、刷新终端中的 DNS、清除 cookie。但是 none 有效。

这是得到 returns:

的错误
error.response : {
    "data": "Bad Request",
    "status": 400,
    "statusText": "Bad Request",
    "headers": {
        "connection": "keep-alive",
        "content-length": "11",
        "date": "Sat, 16 Oct 2021 18:49:44 GMT",
        "keep-alive": "timeout=5"
    },
    "config": {
        "url": "/api/signin",
        "method": "post",
        "data": "{\"params\":{\"email\":\"xxxxxx@gmail.com\",\"password\":\"Aug8162016!\"},\"withCredentials\":true,\"headers\":{\"Content-Type\":\"application/json\"},\"credentials\":\"same-origin\"}",
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json"
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        }
    },
    "request": {}
}

我的直觉告诉我这里有东西。

有什么办法可以得到更实质性的错误吗?

我认为您以错误的方式生成了 POST 请求正文。 尝试

const data = {
    email,
    password,
  };

  axios
    .post(`/api/signin`, // url
      data, // request body
      { // options
        withCredentials: true,
        headers: {
         'Content-Type': 'application/json'
      }
    })

如果还是不行,你可以尝试发送已经字符串化的正文:

const data = {
    email,
    password,
  };

  axios
    .post(`/api/signin`, // url
      JSON.stringify(data), // request body as string
      { // options
        withCredentials: true,
        headers: {
         'Content-Type': 'application/json'
      }
    })

它应该有效

axios.post接受3个参数

1-url

2-正文

3- 选项

axios
    .post(`/api/signin`, 
      data, 
      {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json'
      },

    })