Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

node.js - How to pass multipart request from one server to another in NodeJS?

I have two nodeJS servers, Server 1 gets requests from the client and passes it to server 2 which returns a response to server 1 and it responds to the client. The client uploads a file and it has to be passed the same way as any other rest request that I have.

I use axios on server 1 to send the data to server2 and multer on server 2 to store the file on disk.

I have an issue sending the request from server1 to server2 because the body of the request contains nothing and the request is Multipart. enter image description here

How should I handle the request on Server 1 ???

router.post('/fileUpload', (req, res) => {
    console.log(req.body);
    res.status(200).json({ msg: "Got file" });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use form-data module to send multipart/form-data from nodejs application

Here is the code you can implement on Server1 to receive image file from client and send it to Server2.

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');
});

Here multer is used to handle the uploaded file


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...