NextJS服务器无法接受来自NextJS客户端的POST多部分/表单数据(图像)请求

mo49yndu  于 2023-01-02  发布在  其他
关注(0)|答案(1)|浏览(327)

我无法在NextJS服务器上接收来自NextJS客户端的请求正文。
委托单位:

import { NextPage } from 'next';
import { v4 } from 'uuid';

const submit = async (event: any) => {
 event.preventDefault();
 const postID = v4();
 const inputElem = document.getElementById('imgfile') as HTMLInputElement;

 // @ts-ignore
 const file = inputElem!.files[0];
 let blob = file.slice(0, file.size, 'image/jpeg');
 let newFile = new File([blob], `${postID}_image.jpeg`, {
   type: 'image/jpeg',
 });
 let formData = new FormData();
 formData.append('imgfile', newFile);

 const response = await fetch('/api/hello', {
   method: 'POST',
   headers: {
     'Content-Type': 'multipart/form-data',
   },
   body: formData,
 });
};

const SubmitPicture: NextPage = () => {
 return (
   <div>
     <h2>Google Storage API Test</h2>
     <input type="file" name="imgfile" accept="image/jpeg" id="imgfile" />
     <button onClick={submit}>Submit</button>
   </div>
 );
};

export default SubmitPicture;

服务器:

import nextConnect from 'next-connect';
export default nextConnect().post(async (req: any, res: any) => {
  res.status(200).json('Everything is ok');
  
});

问题是服务器忽略了带有formData主体的请求,如果我发送一个没有主体的请求到同一个地方,它会返回状态200给我。
我已经花了半天的时间在这上面,有点绝望。

06odsfpq

06odsfpq1#

form-data不是常规的带正文的POST请求,需要使用formidable这样的中间件进行解析。
按照以下步骤在NextJS服务器中接受multipart/form-data

安装强大

npm i formidable

安装下一个连接

这是NextJS的中间件库
npm i next-connect

实现NextJS API处理程序

import formidable from 'formidable';
import nextConnect from 'next-connect';

const form = formidable({ multiples: true }); // uploaded files will be an array

// Middleware
async function parseMultipartForm(req, res, next) {
  if (req.headers['content-type'] && req.headers['content-type'].indexOf('multipart/form-data') !== -1) {
    form.parse(req, (err, fields, files) => {
      if (!err) {
        req.body = fields;
        req.files = files;
      }
      next();
    });
  } else {
    next();
  }
}

// Disable NextJS body parsing
export const config = {
  api: {
    bodyParser: false,
  },
};

// Handler
const handler = nextConnect({})
  .use(parseMultipartForm)
  .post((req, res) => {
    // req.files will be an array of files
    // Do something with the files
  });

export default handler;

客户端相同

let formData = new FormData();
 formData.append('imgfile', newFile);

 const response = await fetch('/api/hello', {
   method: 'POST',
   body: formData,
 });

相关问题