Proxy-wysyłanie kilku części w NextJS(również NodeJS)

0

Pytanie

Moim zadaniem było przekazać proxy multipart/form-data przez NextJS trasy api, ale wbudowany analizator ciała łamał przychodzące dane muptipart. Wszelkie inne wtyczki do NodeJS nie pozwalają mi przekazywać za pośrednictwem serwera proxy czyste bajty złożonych danych i tworzyć inne obiekty, które nie są danymi formularza.

Więc jak serwer proxy przekazuje składowe/form-dane w API trasach NextJS bez wtyczek?

multipartform-data next.js node.js proxy
2021-11-23 17:03:25
1

Najlepsza odpowiedź

0

Poniższy kod to rozwiązanie dla pomyślnego przejścia serwera proxy multipart/form-data bez wtyczek do NextJS:

// /pages/api/miltipart.ts

// helpers to generate cookies
import { setCookies } from '@utils/api';
import type { NextApiRequest, NextApiResponse } from 'next';

// turn off default parser for current route
export const config = {
  api: {
    bodyParser: false,
  },
};

const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  // create container for all buffers of multipart/form-data
  const buffers: any[] = [];
  // first of all listen 'readable' event to catch all incoming request data
  req
    .on('readable', () => {
      // read every incoming chunk. Every chunk is 64Kb data of Buffer
      const chunk = req.read();
      if (chunk !== null) {
        buffers.push(chunk);
      }
    })
    // listen on end event of request to send our data
    .on('end', async () => {
        try {
          const result = await fetch('https://google.com/api/upload', {
            method: 'POST',
            credentials: 'include',
            mode: 'cors',
            headers: {
              'Content-Type': req.headers['content-type'] ?? 'multipart/form-data',
              'User-Agent': req.headers['user-agent'] ?? '',
              Authorization: 'Bearer Token',
            },
            // concatination of array of Buffers and store it to body
            body: Buffer.concat(buffers),
          });
          const body = await result.json();
          setCookies(res, result.headers);
          res.status(result.status).json(body);
          return;
        } catch (error) {
          res.status(500).json(error);
        }

      res.status(405);
      res.send('Method Not Allowed');
    });
};
export default handler;
2021-11-23 17:03:25

W innych językach

Ta strona jest w innych językach

Русский
..................................................................................................................
Italiano
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................