将 FormData() 请求从 NodeJS 转发到另一个服务

Forwarding FormData() request from NodeJS to another service

我正在尝试将我的请求从我的 NodeJS 代理服务器转发到另一台服务器。我尝试转发的请求包含 FormData()

我根据 MDN docs

创建了 FormData
const payload = new FormData();
payload.append('addresses', file);  // <---- UPLOADED FILE
payload.append('reason', 'reason');
payload.append('type', 'type');

这就是我将请求发送到我的 NodeJS 服务器的方式

fetch("localhost:3000/v1/addresses", {
  method: 'PUT',
  body: payload
});

NodeJS 服务器位于 localhost:3000

const multer = require('multer');
const upload = multer();

app.put('/v1/addresses', upload.single('addresses'), (req, res) => {
  let options = {
    host: 'localhost',
    method: 'PUT',
    port: 8000,
    path: req.originalUrl,
    headers: req.headers,
    formData: {
      reason: req.body.reason,
      type: req.body.type,
    }
  };

  console.log("reason", req.body.reason) // "reason"
  console.log("type", req.body.type)     // "type"
  console.log("addresses", req.file)     // FILE OBJECT

  const request = http.request(options, response => {
    res.writeHead(response.statusCode, response.headers);
    response.pipe(res);
  });

  request.end();
})

上面的代码,我不确定如何将实际文件发送到其他服务。此外,我没有看到我已传递给服务的 reasontype

同样奇怪的是,我在非代理服务器的传入请求中看到了这一点

PUT /v1/addresses HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 932
Sec-Ch-Ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"
Sec-Ch-Ua-Mobile: ?0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryt2p0AWOqJCnz95hg
Accept: */*
Origin: http://localhost:3000
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:3000/blocklist
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

[object Object]

经过大量的搜索和试验,这个 实际上为我提供了答案

这是来自 post 的代码。

const express = require("express");
const app = express();
const bodyParser = require('body-parser');
var multer  = require('multer')();
const FormData = require('form-data');
const axios = require('axios');
const fs = require('fs');

app.use(bodyParser.json());

app.post('/fileUpload' , multer.single('fileFieldName'), (req , res) => {
    const fileRecievedFromClient = req.file; //File Object sent in 'fileFieldName' field in multipart/form-data
    console.log(req.file)

    let form = new FormData();
    form.append('fileFieldName', fileRecievedFromClient.buffer, fileRecievedFromClient.originalname);

    axios.post('http://server2url/fileUploadToServer2', form, {
            headers: {
                'Content-Type': `multipart/form-data; boundary=${form._boundary}`
            }
        }).then((responseFromServer2) => {
            res.send("SUCCESS")
        }).catch((err) => {
            res.send("ERROR")
        })
})

const server = app.listen(3000, function () {
    console.log('Server listening on port 3000');
});