上传到 NextJS 中间件 API 的图像文件形式显示请求为未定义

问题描述 投票:0回答:0

我正在使用 NextJS 处理表单数据并上传到数据库,但首先通过 NextJS API 中间件来编辑图像。

页面/uploadImage.tsx

客户端代码处理程序。

...
async function handleImageUpload(imageFile: any): Promise<Response> {
    const formData = new FormData()
    formData.append("image", imageFile as File, imageFile.name)
    console.log("FORMDATA: ", formData.getAll("image")) // File object 

    const response: Response = await fetch(`${host}/api/image`, {  // host is localhost:3000  
      method: "POST",
      body: formData,
    })

    return response
  }
... 

页面/api/图像/index.ts

处理图像的中间件/后端。

export default async function handler({ req, res }: handlerProps) {
  console.log("METHOD: ", req)  // undefined 
  if (req.method == "POST") {
    const form = new Formidable.IncomingForm()

    try {
      form.parse(req, (error: any, fields: any, files: any) => {
        if (error) {
          res.status(500).send({ message: `${error}` })
        }

        ... handle image and upload to database ...  

        })

        res.status(200).send({ message: "Success" })
      })
    } catch {
      res.status(500).send({ message: "Error on processing image" })
    }
  } else {
    res.status(404).send({ message: "POST only supported" })
  }
}

请原谅混乱的错误处理,我知道这不是好的做法。

我的问题在

console.log("METHOD: ", req)  // undefined
。这是如何返回未定义的?很明显 API 路由是正确的,因为代码到了这一点,但我需要帮助来调试。

我在想我的标题在前端是错误的。

我试过添加到标题中,这导致了同样的问题:

 headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },

我也在标头中尝试了 JSON,结果相同:

const response: Response = await fetch(`${host}/api/image`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    })
javascript node.js typescript next.js
© www.soinside.com 2019 - 2024. All rights reserved.