What’s the difference between res.send and app.post? - javascript

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.

Related

res.send token and then redirect

I have an express app that upon calling a get request immediately returns a string token, then runs a python code. The python code after some time creates a json file that I need to send in another post request.
This python code may be called by different users that's why i need to assign them a token a soon as the app is called.
In the post request i'll also be modifying the json file and then sending it back
I'm trying to do res.send the token and then res.redirect to the post request, but i know it's impossible. Is there any other way i could send the token or redirect to the post request?
app.get('/', (req, res) =>{
res.send(token())
runPython((code)=>{
*takes around 10 sec*
res.redirect('/post')}}
app.post('/post', (req, res)=>{
*do stuff to file*
res.sendFile()
You cannot send multiple responses back to the client separated in time. You get ONE http response. So, once you've done res.send(token()), then that http request is done. You can't send any more data as part of that http request.
As you describe things, here are some of your options:
Combine both into one response. Wait to send the token until you have the python response too and then send them both in one JSON response. You won't be able to do a res.redirect() if you're also sending data back. So, you could send the redirect location back in the JSON and have the client manually do the redirect (by just setting window.location to a new URL). Presumably, there is client-side Javascript on the receiving end of this anyway since some form of code has to receive the token anyway to do something useful with it.
Use websocket/socket.io connection for subsequent server-initiated communication. Have the client connect a webSocket or socket.io connection. You can then response with the token and then later when the python has finished, you can send additional data over the websocket or socket.io connection. This will require additional code to be able to associate a particular websocket/socket.io connection with the client that made this request so you can tell which websocket/socket.io connection for this request to send a notification over.
Client-side polling for completion of python operation. Have the server send back the token and also send it some sort of request ID and then the client can poll the server every few seconds to ask the server if that python operation for that request ID is now done. When it gets a response from the server that the python is now done, then the client can manually redirect itself to /post to fetch the final data.

can someone please explain REQ in express plz

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.

Express HTTP Only Cookie issues

Here is the request being made to the api.website.api server from website.app.
website.app has a http secure cookie
I'm assuming the http cookie is being sent along in the request?
axios.get('api.website.app/route',{withCredentials: true}).then(res => {
// some code
})
In an auth middleware function, I call req.cookies.access_token but it's not being verified on the request. It seems the server isn't getting the cookie from the http request. I'm trying to get the server to verify the token but it's not doing so.
This is the middleware function I am using
The route in express using the auth middleware.

Request objects and response object

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

Changet POST to Delete

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.

Categories

Resources