HTTP "redirect" with node.js - Is there a module? - node.js

not sure if I picked the right terminology, what I want to do is the following:
A node.js module receives http requests of all kinds (GET, PUT, POST ...). It should take these requests and route them to a different URL but keep all other input parameters as it received it.
The response coming in should then be handed back to the calling party.
I realized it with express and https modules for a simple GET and it worked. Before I start coding down the remaining stuff I was wondering if there is a module available for such a URL "redirect"?
Example:
http://server1/api/[parameters] + [body] => https://server2/api/[parameters] + [body]
and handing the response back.
Hope I was able to explain.

To redirect someone to another url you can use the code below:
response.writeHead(302, {
'Location': 'your/404/path.html'
//add other headers here...
});
response.end();
with this response you must also include the appropriate status code for redirection(301, 303) according to your situation.
You can see full list of status codes here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

Related

Unable to get redirect response from Node server using res.writeHead() and .end()

I'm writing a server in Node.js. I've been using the send-data/json package to send responses, with much success. For example, at the end of my API call I use this code:
sendJson(res, res, {some: content})
This works great. However, I have a need to implement a URL redirect in one of my API endpoints. The code I am seeing everywhere to do this looks like this:
res.writeHead(302, {Location: 'http://myUrl.com'})
res.end()
However, this change causes my server to stop sending responses on this endpoint.
What am I missing?
Note: this is vanilla Node without Express.
Update: to clarify, based on contributions in the comments, this is the result of a GET request, so I expect that redirects should be enabled by default. I am still curious why no response is coming back from the server at all, regardless of whether it is an erroneous redirect attempt or a successful one.

How to send a http response using koajs

I'm trying to validate a webhook via facebook. So facebook hits my url my-url/facebook/receive within my route in nodejs i'd do res.send(req.query['hub.challenge']); to send an http response.
I'm using KoaJS. From what i understand, Koajs merges the request and response object into ctx but when reading through the docs I can't find anything along the lines of ctx.send or similar to send a http response.
Can anyone give me some direction or links.
Thanks.
To send the body of a response, you can simply do ctx.response.body = 'Hello'. There are many aliases attached to ctx, so you don't necessarily have to reference the response or request yourself. Doing ctx.body = 'Hello' would be the same as the code above.
If you wanted to set headers, you would use the ctx.set() method. For example: ctx.set('Content-Type', 'text/plain').
To access the query parameters, you would use ctx.request.query['some-key'] (or simply the alias ctx.query['some-key']).
All of the different request/response methods are documented pretty well at the Koa website along with a list of aliases attached to ctx. I highly recommend you give it a read.

NodeJS HTTP - Removing a header from request to be proxied

I have a NodeJS proxy service which obfuscates some data and forwards the request to another service. Due to some details surrounding how we, and the servcie we're proxying to handle authentication, we need to remove a certain header from the incoming request before we proxy it.
I saw some documentation about request such as: "This object is created internally and returned from http.request(). It represents an in-progress request whose header has already been queued. The header is still mutable using the setHeader(name, value), getHeader(name), removeHeader(name) API."
But then the same documentation says the headers are read-only. I also saw some documentation that showed those methods (removeHeader, etc) being available, and others that don't list it.
Can someone tell me if there's a way to remove a header from the request object itself before copying the headers over? If not is there an easy way to copy over all the headers except the one I want to leave out?
Came here looking for a solution, but for node-http-proxy. You can do it by listening to proxyReq event on the proxy and then calling removeHeader on the proxy request object, like so
myProxy.on("proxyReq", function(proxyReq, req, _, options) {
proxyReq.removeHeader("x-my-header");
});

ExpressJS Redirect And Return Data For Request

Say I'm going to redirect from /1 to /2. Obviously I can just redirect, and have the browser send a separate request to /2.
Is there a way that I can call res.location('/2') and then return the data from that url as if the request to that url was a GET request?
Thanks!
Edit: The redirect from 1 to 2 will happen on a validated POST from 1, which can either fail, going back to 1, or succeed, redirecting to 2. What I want is something like
app.post('/2', function(req, res) {
if (validate(req.body) {
res.location('2');
res.send(app.getResponseFor('1'));
} else {
res.render('2');
}
});
I think one way to do this is to rip the function out of 1, and just have both 1 and 2 call into it. Maybe someone can think of a more elegant way!
That's more like a "design issue". You could implement this in two ways:
With smart client:
The client requests for the /2 resource in ajax mode,
The server responds with a 4xx code (eg 401 for unauthorised)
The client catches this exception (error case) and requests the resource from /1 without redirecting the user
With Helpers in server side:
You split your application logic in a classic MVC architecture,
The controllers of /2 endpoint use some helper functions so they can check the condition of the request
If the request doesn't follow some certain rules, a helper function provide the controller with the appropriate content, as if the client had requested the /1 endpoint
Hope this helps.
Cheers.

Fetch post data after a request in NodeJS

i' m a bit new to Node, so question may be stupid...
I am sending a POST request to a website (through http.request) and I want to be able to use the invisible POST data I get along the response.
I hope this is achievable, and I think so since I am able to preview those data in Chrome debugger.
PS : I understand that we can use BodyParser to parse and get those while listening for a POST call server side, but I have found no example of how to use it coupled with an http.request.
Thanks !
If the body of the HTTP response contains JSON, then you need to parse it first in order to turn it from a string into a JavaScript object, like this:
var obj = JSON.parse(body);
console.log(obj.response.auth_token);
More info on various ways of sending a POST request to a server can be found here: How to make an HTTP POST request in node.js?
Edit : So we figured it out in the comments. The value I needed was in the form to begin with, as a hidden field. My error was to think it was generated afterward. So I'll just grab it first then login, so I can use it again for future POST requests on the website.

Resources