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!
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.
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.
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.
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.
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();
});
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With