Request objects and response object - javascript

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

Related

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

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.

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.

How to access HTTP headers of request in AngularJS

I know I can access an HTTP request's GET parameters in AngularJS with
$location.search().parameterOfInterest
But how do I access HTTP headers of the request?
I'm not using $http here. I'm asking about request to an AngularJS web page.
This question and answers makes me believe this is could be not possible:
Accessing the web page's HTTP Headers in JavaScript
You can use a request interceptor that is called with an HTTP configuration object. An HTTP configuration object has a header property that you can freely access / modify inside your interceptor.
The response object of promise also has a header property that you can access.

Apollo Client sending OPTIONS instead of GET HTTP method

I'm having trouble understanding Apollo Client library as it does not work as intended. Instead of sending the GET HTTP method, it sends the OPTIONS HTTP method even though I've put to use GET only when retrieving data from GraphQL server.
const client = new ApolloClient({
link: ApolloLink.from([
new MeteorAccountsLink(),
new HttpLink({
uri: 'https://selo-comments.herokuapp.com/graphql',
useGETForQueries: true
})
]),
cache: new InMemoryCache()
});
Console log from the browser:
OPTIONS https://selo-comments.herokuapp.com/graphql?query=%7B%0A%20%20comments(id%3A%20%22TFpQmhrDxQqHk2ryy%22)%20%7B%0A%20%20%20%20articleID%0A%20%20%20%20content%0A%20%20%20%20userId%0A%20%20%20%20createdAt%0A%20%20%20%20commentID%0A%20%20%20%20votes%0A%20%20%20%20blockedUsers%0A%20%20%20%20__typename%0A%20%20%7D%0A%7D%0A&variables=%7B%7D 405 (Method Not Allowed)
Which obviously means that the HTTP method is incorrect even if it has the query parameter in the url. If you query that url using Postman or simply navigating to the url using browser's address bar, you will get GraphQL data. I have to use https://cors-anywhere.herokuapp.com/ in order to execute the query successfully.
What am I doing wrong?
The options request is probably a preflight request for CORS.
A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood.
It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header.
You probably need to configure your server to allow cross origin calls.
Maybe you can find some inspiration here to get u started. Allow CORS REST request to a Express/Node.js application on Heroku

nodejs returns config and headers information

HI Why is my express is returning headers and config objects details, where as I am just returning the object data.
This is a standard response from a node server. This response contains headers information,status code and other additional information. You can edit these values in your express configuration. The actual data sent from the server is inside data property of response.

Categories

Resources