Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to res.send to a new URL in Node.js/Express?

Given a GET request to URL X, how should you define res.send such that it provides a response to a completely separate URL Y?

i.e.

app.get('/', function (req, res) {
    res.send to a new URL external of the app ('Success')
});

Thanks and apologies in advance for ignorance on the topic!

like image 732
Matthew Foyle Avatar asked Nov 08 '16 22:11

Matthew Foyle


People also ask

How do I redirect a URL to another URL Express?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.

What does Res send () do?

send() Send a string response in a format other than JSON (XML, CSV, plain text, etc.). This method is used in the underlying implementation of most of the other terminal response methods.

What is RES Send Express?

The res object basically refers to the response that'll be sent out as part of this API call. The res. send function sets the content type to text/Html which means that the client will now treat it as text. It then returns the response to the client.

What does res redirect do in Nodejs?

The res. redirect() function redirects to the URL derived from the specified path, with specified status, a integer (positive) which corresponds to an HTTP status code.


2 Answers

You want to redirect the request by setting the status code and providing a location header. 302 indicates a temporary redirect, 301 is a permanent redirect.

app.get('/', function (req, res) {
  res.statusCode = 302;
  res.setHeader("Location", "http://www.url.com/page");
  res.end();
});
like image 164
Dan Nagle Avatar answered Sep 19 '22 21:09

Dan Nagle


You can only send response to the request source, which is the client. There is no such thing as sending response to another "external-url" (or another server).
However, you CAN make a request to another server, wait for it's response, and respond to our client.

app.get('/', (req, res) => {
    
    var requestOptions = {
        hostname: 'serverB.com', // url or ip address
        port: 8080, // default to 80 if not provided
        path: '/take-request',
        method: 'POST' // HTTP Method
    };

    var externalRequest = http.request(requestOptions, (externalResponse) => {
        
        // ServerB done responding
        externalResponse.on('end', () => {
            
            // Response to client
            res.end('data was send to serverB');
        });
    });
    
    // Free to send anthing to serverB
    externalRequest.write(req.data);
    externalRequest.end();
});
like image 37
rocketspacer Avatar answered Sep 20 '22 21:09

rocketspacer