Transferring Files from express js to another server

789 Views Asked by At

I have a situation where I am sending a file from Jquery to my express sever, and I need to transfer that request to another server without parsing the file in express server. here is the code snippets I have used till now Jquery

$.ajax({
            url: 'api/auth/handle',
            type: 'POST',
            data: data, // formData
            cache: false,
            dataType: 'json',
            processData: false, // Don't process the files
            contentType: false, // Set content type to false as jQuery will tell the server its a query string request
            success: function (data, textStatus, jqXHR) {
                console.log("success");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // Handle errors here
                console.log('ERRORS: ' +textStatus);
                // STOP LOADING SPINNER
            }
        });

Express js code

module.exports.handleFile = (req, res) => {
    console.log(req);
    let data = request.post("http://localhost:5002/files/pdf", function (err, resp, body) {
        //console.log(err);
        if (err) {
            console.log('Error!');
        } else {
            console.log('URL: ' + body);
        }
    });
    let form = data.form();
    form.append('file', '<FILE_DATA>', req);
    res.status(200).send({ "success": "success" });

};

The problem is I am not getting the form data on my second server. Any suggestions would be helpful.Thanks

1

There are 1 best solutions below

4
On BEST ANSWER

I would suggest using a proxy module for Node.js/Express. One of the available is called express-http-proxy

Example usage from their documentation:

var proxy = require('express-http-proxy');

var app = require('express')();

app.use('/proxy', proxy('www.google.com', {
  forwardPath: function(req, res) {
    return require('url').parse(req.url).path;
  }
}));

So you can redirect a request of your choice to another server.

See https://github.com/villadora/express-http-proxy for more info!