Server side vs client side fetch api - node.js

So, in the browser, fetch returns a promise that returns a promise. The first for an OPTIONS http call which is sometimes a 'preflight CORS' thing, and the second a response to your original request.
In Node.js when you use the https.request() function or many of the libraries, this pattern isn't followed. Is that because there is no options call when you make an http call from a server?

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.

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.

Is it required to send a response in every request no matter GET or POST in nodejs?

I defined my_function inside app.post('/someRoute',my_function) in nodejs which is used for making an http-request(posting data) to another server.
However it seems that my_function will run twice when I do not defined any response to the browser inside my_function.
What will be the reason for this? And is it required to send a response in every request no matter GET or POST in nodejs?
Thanks!
Whenever you do not define a response to a function/route handling get or post requests, the request response cycle will not end and thus the request keeps running until it times out because it took too long to get a response from the server. It is thus important to define a response to every request.

Node and Express, getting all (custom) methods with .all()

In Node and Express, I'm trying to get all traffic sent to a URL like this.
APP.all('/testCase', function(req, res) {
console.log('Im called with the method: ' + req.method);
});
If I now do:
curl -X GET http://localhost:3000/testCase it works fine, I get the response: Im called with the method: GET
But when I do:
curl -X INSERT http://localhost:3000/testCase I'm getting: curl: (52) Empty reply from server
What Am I doing wrong? I will have many custom methods
The INSERT method is not supported by the node http parser. To see a list of the HTTP methods supported, you can run node -pe "require('http').METHODS". In order to support custom HTTP methods, one would have to patch core itself (specifically the http parser).
app.all(path, callback [, callback ...])
This method is like the standard app.METHOD() methods, except it
matches all HTTP verbs.
It’s useful for mapping “global” logic for specific path prefixes or
arbitrary matches. For example, if you put the following at the top of
all other route definitions, it requires that all routes from that
point on require authentication, and automatically load a user. Keep
in mind that these callbacks do not have to act as end-points:
loadUser can perform a task, then call next() to continue matching
subsequent routes.
The most commons HTTP methods is:
GET
HEAD
POST
PUT
DELETE
TRACE
CONNECT

Understanding WSGI

I am trying to understand the functionality of WSGI and need some help.
So far I know that it is kind of a middleware between servers and applications, used for interfacing different application frameworks (that reside in the server side) with the application, provided that the framework in question has a WSGI adapter. Continuing the theoretical part, I know that for server to communicate with the application, server calls a callable (that takes two arguments: environment variables and start_response function). Here start_response function is provided by the server (?) and used by the application with a response status and header followed by response body.
I understand little of what I wrote above, so here are newbie questions:
1) What is the general call flow ? Application will provide the server with a callable and then server would invoke the application using that callable and using env_vars and start_response function as arguments?
2) What confuses me the most is that the application is sending the request headers and then it sends the response body as well. What type of request is this ?
Please enlighten me as I am unable to get my head around this stuff.
Thanks!
The call flow is as follow:
The server got a http connection,
server parsed the http request line and headers, read the body,
server populates the environ dict according to the request,
server calls application callable with environ and start_response as arguments,
application callable calls start_response with response status and response headers,
application return response body to the server,
server send the http response to the client.
For your second problem, the request/response is an interface defined by wsgi protocol (e.g. status = '200 OK', response_headers = [('Content-type', 'text/plain')]), not the same thing with http request/response.
You can browse the stand library module wsgiref as reference.

Resources