I dont get how we use req in express. I undrstand that the server can respond back to client,but when it comes to req object im confused. Is req when the server is asking for somethong from the client?
HTTP is an application, client-server protocol. Everytime that a client want the server to perform an action, it has to make a request. The HTTP protocol defines a set of actions or verbs that are available to the client so it can make each request using one specific verb (GET, POST, PATCH, PUT, DELETE, etc). It doesn't matter what verb the client uses, only the client can initiate a comunication with the server using one of that verbs. So this is how exactly an HTTP GET request looks like:
GET / HTTP/1.1
Host: example.com
User-Agent: curl/7.69.1
Accept: */*
The first line contains the verb used, in this case GET, the path requested, in this case /, and the protocol version, in this case HTTP/1.1. The next lines, are a set of key value pairs called the headers of that request, which can define a lot of aspects of the request made by the client to the server. By the way, an HTTP server never could or will start a request to a client, a client always is the one that make the request, and the server is always the one that response that request. One of the aspects of that request for example, is the destination host, that is present in the header host with the value of example.com. Bellow of the headers, all the HTTP requests have a blank line and then the body of the request, which normally contains the data that is sent from the client to the server. In this case, no data body is sent on the request.
Express is an HTTP server based on the HTTP module available on Node.js. Express simplifies the way that the native Node.js HTTP server works. Here is tipically how an Express app looks like:
const express = require('express');
const app = express();
// This is called a router
app.get('/path', (req, res) => {
// This router will perform some action with the req object
// And will send a response to the client
});
So, on the example above, the method app.get(...), available on Express applications, allows the server to deal with the GET requests that come from the client. The app.get() method takes two arguments, a path and a callback function. The path argument represent the string that goes after the name server, for example, in the URL www.example.com/test, the hostname is www.example.com, and the path is /test. That method app.get() is also called a Router. So, the router of the example will deal with the GET requests to that server which also define /path value as the path the request is sent to. Once a request to the server fit those two conditions, that callback will be triggered.
So, finally we get to the answer. The res variable is an object (a set of key-pair values separated by commas and locked into curly braces), that contains the data of the HTTP request, into a friendly legible object. For example, if you want to print to the console the path that the client used, you can print it like this console.log(req.path), or you can get all the headers of that HTTP request, you can use console.log(req.headers). The req object is one of the 5 main objects in Express, in fact the Express documentation defines a ton of methods that you can use with the request object (req). To get deep into the request object, you can see the official Express documentation in this link. The callback defined into the router, can use the req object, to extract information of the client's request, process it and return a response to the client later.
With an express server, you get two objects passed to a request handler.
req is data about the incoming request (things that were sent from the client). It contains the headers on the request, it contains a parsed query string, it contains the URL path, it's generally the object where middleware puts things for request handlers to use. While Express adds a bit more to this object, you can see the general concept of the req object by looking and the http.IncomingMessage object documented here. This is what the object starts out as and then Express adds more to it. The express version of the object is documented here.
res is the response object. This is all about sending a response. It will hold the outbound headers you want to send with the request. It contains the methods you use for sending a response. The core object is an http.ServerResponse object documented here and then Express adds some more things to the object on top of that which is document here.
Related
I’m new to express and HTTP. The express library has app.get, app.post and res.send. As I understand it, app.get uses/is used with GET and app.post POST. Does res.send call POST?
res.send() sends a response to an incoming http request that has come into your http server.
app.post() registers a request handler with Express for a specific URL in your http server and for POST requests so that when your Express server receives a POST request at that URL, it will call this request handler.
Here's an example of res.send():
// configure request handler for GET request to /
app.get("/", (req, res) => {
res.send("hi"); // send response to incoming http request
});
Here's an example of app.post():
// this middleware reads and parses the body for content-type
// of application/x-www-form-urlencoded
app.use(express.urlencoded({extended: true}));
// configure request handler for POST request to /login
app.post("/login", (req, res) => {
// in a real request handler, this would be some sort of username
// and password comparison in a database and using appropriate crypto
if (req.body.username === "John" && req.body.password === "foobar99") {
res.send("login successful");
} else {
res.status(401).send("Login failed");
}
});
The express library has res.get and res.send. As I understand it, res.get uses / is used with GET.
You are perhaps confused because there is no res.get. Perhaps you meant app.get()? If so, app.get() configures a request handler for an http GET request to a specific URL. So, app.get("/books", ...) might display a page of all available books.
Does res.send call POST?
No. res.send() sends a response to an http request.
Here are the steps you can think of.
An http client (such as a browser or any piece of code) creates an http request and sends that request to a server.
That request will have both an HTTP verb such as GET, POST, PATCH, etc... and it will have a URL such as /login or /books.
The web server that the request was sent to receives that request. In the case of a web server using the Express framework, the Express server looks through its list of already registered routes (these routes were previously registered with app.get(...), app.post(...), app.use(...), etc... These are essentially listeners for specific routes. If the Express server finds an already registered route that matches both the http request verb and the URL, then it calls that route handler and pass it three arguments (req, res, next).
When the request handler code gets called, it can examine the req object to see any data about the incoming request such as the exact URL, any http headers on the request and so on. It can use the res object for sending a response such as setting any http headers on the response, setting content-type, setting an http status code for the response, creating and sending the body of the response, etc... res.send() is one way to send the response. There are also others such as res.sendFile(), res.json(), res.sendStatus() and so on...
After one of these methods is called that sends the response, then the underlying engine sends that http response back to the client that sent the original http request and the HTTP request/response is considered complete.
Those are two different modules/objects..
The Express Router supports HTTP methods for the server to listens and respond to - .get(), .post(), .put().
One of the arguments passed through the chain of middleware and handlers is the Response, which has a .send() method to send its response back to the client. The Response object can also be enhanced to send JSON, etc.
In express.js, middlewares can change request object and response object. So, my question is what exactly these request object and response object are and what do they contain.
From expressjs documentation a request is:
The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
And the response:
he res object represents the HTTP response that an Express app sends when it gets an HTTP request.
Basically you use a request to know what the client is asking for.
And you use the response object to send the response data to the client.
Had the same questions when i started with express. I found a nice article, explaining my questions.
http://www.murvinlai.com/req-and-res-in-nodejs.html
UPDATE
from the page:
What is Req & Res?
Req -> Http (https) Request Object.
You can get the request query, params, body, headers and cookies from it.
You can overwrite any value or add anything there.
However, overwriting headers or cookies will not affect the output back to the browser.
Res -> Http (https) Response Object.
The response back to the client browser.
You can put new cookies value and that will write to the client browser (under cross domain rules)
Once you res.send() or res.redirect() or res.render(), you cann do it again, otherwise, there will be uncaught error.
Me too had this same doubts.
Request Object
The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on
Response Object
The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
Reference Link
I Changed a http method POST to DELETE and when i click a button nothing happens.
what i have but works
router.post('/', function(req, res) {
//do something
});
what i want
router.delete('/', function(req, res) {
//do something
});
The important thing to remember when defining your server side routes is that even though two route definitions may have the same path but different HTTP verbs, they are not treated as the same by the RESTful API infrastructure. It is essentially like defining two completely separate functions in a class. The POST route will only ever be called if a POST request is sent to the applicable route, while the DELETE route will only ever be called if a DELETE request is sent to the applicable route. The execution of those two different route definitions is completely dependent on the HTTP verb that is specified in the HTTP request object that is sent to your API. You can read about all of the different HTTP request methods here.
Without being able to see the code for your button, all I can say is that in order to fix your broken code, you need to make sure that your HTTP request that is being sent to the server is specifying a DELETE HTTP verb instead of the original POST HTTP verb that your code was originally specifying when your code initially worked.
I created a small server which, for now, just outputs the request.url:
const http = require('http');
http.createServer(onRequest).listen(8080);
function onRequest(clientRequest, clientResponse) {
console.log(clientRequest.url);
}
Using the Electron APIs we can set up a proxy: to proxy all the urls through this server.
So, I'm running my server on localhost:8080 and use the --proxy-server http://localhost:8080 to redirect the traffic through my proxy server. This allows me to change some snippets in the HTML and only then render it in Electron.
When I access http://ionicabizau.net the request.url on the server side is http://ionicabizau.net.
How come that we can override the request url in such a way? What does Electron in the background?
First I thought that it just has to do with appending it like this:
http://localhost:8080/http://ionicabizau.net
But actually, that arrives on the server like /http://ionicabizau.net (notice the first slash).
What's the magic that Electron does to change the url of the request object?
When Electron (or anything else) makes an HTTP request, it connects to the target server and port and sends a message like the following:
GET / HTTP/1.1
Host: www.example.com
Most servers interpret this as an HTTP request for the full URL http://www.example.com/. When you specify a proxy server, that affects what server the HTTP client connects to, but it doesn't change the content of the request (so the requested URL is still http://www.example.com/).
So there's really nothing special that Electron needs to do to "override" the request URL... any HTTP client specifies the request URL as part of the message it sends to the server, and this is independent of which server that message is sent to.
I'm going to create an /api endpoint blindly proxying requests and responses back and forth to the legacy RESTful API system (written in Ruby and hosted on a different domain).
This an intermediary transitional step, so that should just work.
So, I see how that can be easily achieved with app.all(). But as the API is RESTful I do also have to maintain the HTTP verb used for the request - so, can I detect it from the req object? If not, of course I can subscribe 5 handlers for GET, PUT, POST, DELETE, OPTIONS, but it will be much better to avoid this.
Also, how should I deal with the request body (query string and payload)?
I assume I'll need to manually recreate the query string from the parsed req.query and pass req.body to request https://github.com/mikeal/request as is - is it right?
I guess you all need is req.method. And to deal with body, add express.bodyParser() middleware.
If you just want to pass requests and return the response then you are looking for a proxy.
I'd recommend checking out node-http-proxy. Just load the proxy library, init a proxy, and proxy all requests.