NodeJS HTTP - Removing a header from request to be proxied - node.js

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

Related

Why do we need to add .end() to a response?

Currently building a RESTful API with express on my web server, and some routes like the delete route for a document with mongoose ex. await Note.findByIdAndRemove(request.params.id) response.status(204).end() send response statuses with end()
Why do I need to add the .end()? What in these cases, and why cant one just send response.status(204)
With some responses that return json, the response.status(201).json works fine
Only certain methods with Express or the http interface will send the response. Some methods such as .status() or .append() or .cookie() only set state on the outgoing response that will be used when the response is actually sent - they don't actually send the response itself. So, when using those methods, you have to follow them with some method that actually sends the response such as .end().
In your specific example of:
response.status(204)
You can use the Express version that actually sends the response:
response.sendStatus(204)
If you choose to use .status() instead, then from the Express documentation, you have to follow it with some other method that causes the response to be sent. Here are examples from the Express documentation for .status():
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')
Since all three of these other methods will cause the response to be sent and when the response goes out, it will pick up the previously set status.

Why do we add properties to request object?

I can't understand why do we add properties to request object?
As I know, the request object comes from the front end side and if any information is needed or they have, the frontend side should attach it to the request object and send it to backend side like a cookie or JWT token, etc.
And after we got that information in the backend side we can add/update more properties to the response object, like new JWT token, new session ID, etc.
But I see in backend codes, they also add properties to request object and this is vague to me. I don't know why the backend side should add something to the request? Maybe because of the internal transactions between the different middleware this happens? I mean middleware1 adds something to the request object and sends it to the middleware2 in backend side?
For example I can't understand why do we add something to req.session not res.session? Because as I understand this data should be passed to the frontend side to be added into their next request.
But if there is any other reason for adding properties to req object instead of the res object, please let me know?
Mutating the request object by adding additional properties is the primary method of passing additional data between middlewares within Express. Since the request and response are passed to every middleware, this is the only chain that gives you continuity between middlewares.
(You will also see some passed on the response object as well, but in general it's most common to see it on req).
Note that you need to avoid collisions with Express's properties and methods as well as the underlying connection objects from Node.

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

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

204 error code then 500 error code responses

So I have an application which needs to send data to the API which is created by our team leader using NodeJS with Express.js.
On my end I have laravel application which using VueJS for the UI. Inside the Vue JS component. I am using axios to request to the API.
axios.post('https://clearkey-api.mybluemix.net/sendcampaign', request)
.then(function(response) {
//console.log(response);
})
However, it returns 204 which means according to this https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
204 No Content
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
Then next it returns 500 Internal Server Error. So in my opinion it returns this error because there is no content to be returned from the server?
Can you tell me other possible problems why it return that response?
Check if the "HTTP method" of the 204 is OPTIONS and if the method of the 500 is POST.
If both are like that, then you are seeing first a CORS pre-flight request (the OPTIONS that returns 204) and then the actual request (the POST that returns 500).
The CORS pre-flight request is a special HTTP message your browser sends to the server when the webpage and the backend are hosted at different addresses. For example, if your website is hosted at http://localhost but the backend you are trying to access is hosted at https://clearkey-api.mybluemix.net.
The reason of the 204 just means your backend endpoint is correctly setup to handle requests for /sendcampaign (you can ignore it). The reason of the 500 is because of some exception in the implementation of the function that handles that endpoint.

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.

Resources