I have a confusion while using the bodyparser.Why do we actually need bodyparser when we have json.stringify(to convert object to string) and json.parse(to convert JSON to object)
is it because using it in our app.use() automatically applies the middleware during the interchange of data between client and the server? and we don't need to specify each time when the sending the data from client to server and vice versa?
and if it is so what is the difference between urlencoded and json in bodyparser?
Yes, you are correct. Body-parser is a middleware that automatically parses incoming request bodies and makes the data available in req.body property. It eliminates the need to manually parse the request body each time a request is made, saving time and reducing the risk of bugs.
The difference between urlencoded and json in body-parser is the format of the incoming request body. urlencoded is used when the request body is encoded as URL-encoded strings (i.e. x-www-form-urlencoded) while JSON is used when the request body is in JSON format. By using both, you can handle different types of request bodies.
Why do we actually need bodyparser when we have json.stringify(to convert object to string)
The body parser is also responsible for reading the data from the network stream of the HTTP request in the first place. You can't parse data until you have it.
what is the difference between urlencoded and json in bodyparser?
They parse bodies written in different data formats. The urlencoded format is the default encoding format for a <form>.
Related
We have a method res.json to send file in NodeJs but what would happen if we send a json file using res.send. What will be the consequences and why should we avoid doing this thing?
from express documentation:
res.json([body])
Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().
The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.
res.send([body])
Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.
This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the Content-Length HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.
When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream”, unless previously defined.
When the parameter is a String, the method sets the Content-Type to “text/html”.
When the parameter is an Array or Object, Express responds with the JSON representation.
I assume you are talking about ExpressJS:
Whenever an Express application server receives an HTTP request, it will provide the developer with an object, commonly referred to as res. For example,
Example
app.get('/test', (req, res) => {
// use req and res here
})
The res object basically refers to the response that'll be sent out as part of this API call.
res.send:
The res.send function sets the content type to text/Html which means that the client will now treat it as text. It then returns the response to the client.
res.json:
The res.json function on the other handsets the content-type header to application/JSON so that the client treats the response string as a valid JSON object. It also then returns the response to the client.
conclusion:
With res.send you have to take care of converting it to a JSON object if needed, whereas with res.json this is done automatically.
I'm building a react application and I use Node (with Express) as a proxy-server. I send data from react app to node-express, then in Node I use that data to form URI and to make requests to another server.
My question is this: Shouldn't 'content-type': 'charset: utf-8' be enough when I send data including greek characters to Node? For example, I make a post request (using Fetch) to Node and I send code 'ΠΕ0001' using the header I already mentioned. Why do I get the error 'Path contains unescaped characters'? When I use encodeURIComponent it does work, but why 'charset: utf-8' is not enough?
Just setting the header 'content-type': 'charset: utf-8' is not enough. Essentially with this Header you're just telling the server (Node in this instance), that the data you send is in utf-8 format, which it should expect anyway.
Your string, however, is in UTF-16 format, because the letter Π needs two bytes to be represented..
You can read more about character encoding here.
Hence you need encodeURIComponent first. In our case, Π is then represented as %CE%A0, which are its byte's representations in UTF-8.
use this method JSON.stringify() to convert data to json object.
then pass that json object into encodeURIComponent()
then call fetch method
I'm building a simple proxy with php for server side and javascript for the client side (browser).
the php server receives post requests with json data , something like that:
{headersArray: ["Get /someurl...","Cookie: some cookie"],url...}
than after extracting the headers and the url the php code uses curl to fetch the resource , and at this point i would like to construct a response object on the client via the "Response" constructor , so i need to transmit back to the client the headers also so i thought about constructing again a json object which will contain the headers and the response body , but a lot of servers uses gzip encoding, can i insert the gzip encoded response body as a json property and safely transmit it back to the client? would i need to decode it on the client browser? does it add a lot of overhead? any better ideas?
I know about body-parser and what it does. I'm curious to know where is data in request while using express. In which format does is exist before body-parser parse input.
// parse urlencoded types to JSON
app.use(bodyParser.urlencoded({
extended: true
}));
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));
Where will be data if none of these is used? In which format will it be available?
This is pretty thoroughly covered in the Node documentation.
The request object that's passed in to a handler implements the ReadableStream interface. This stream can be listened to or piped elsewhere just like any other stream. We can grab the data right out of the stream by listening to the stream's 'data' and 'end' events.
Express is really applying extensions to the Node.js HTTP server features, including extending the native Request and Response objects. Therefore, you can likewise treat the Express request just like a native request object as well
A POST request is made to a specific path (with optional query parameters). The body of the request is where the POST data is put. Express by default reads the headers of the request, but does not read the body of the request. It is the body-parser middleware's job to read and parse that request body so that its data is easily available to you.
Where will be data if none of these is used? In which format will it be available?
So, if you don't have the body-parser middleware installed or don't have a version of the middleware that matches the format of the data, then the body will still be in the incoming request stream, waiting to be read. The req parameter to the request is a readable stream. The data will be waiting to be read in that stream.
The format will be whatever the content-type header in the request says the format will be. For a classic form post, it is typically application/x-www-form-urlencoded, but it can be set to other types such as application/json. It is the requester who decides what content-type to set and then they must encode the data in the body according to that standard.
For things like file uploads, other content types such as multipart/form-data may be used.
If I use:
xhr.setRequestHeader("Content-Type", "application/json");
Am I forced to receive a json response also ? Or I can receive a html response instead?
If I can receive any format I want, what is the best way to dynamically manage this 2 aspects:
the way that I will parse the response (to parse a json or not)
what Accept header to use
For example my function should set:
xhr.setRequestHeader('Accept', "application/json");
in case it waits for a json response, but also do a json parse on the response also, but in case it's a html reponse there is no need for something like this.
So is there any way to manage dynamically the response handling?
Actually content-type is the data type you want to send to the server . on the other hand data-type or as you mention accept is used to negotiate with server which kind of data you are expecting . So as a client you can request multiple data types e.g
httpRequest.setRequestHeader('Accept', 'application/json, text/xml');
But you are responsible to handle the data-type you mention to parse on client side . on server side it is decided by server during negotiation time to produce your desired data-type such as xml,json ,html etc.
So finally you are you are only responsible for the data format you requested. if you request json , then probably the server response data will be json not xml but you have to remember it depends on server side which data-type choice it has, most of the time its json or xml (will known data exchange fromat) then you dont have to request html ,and this mechanism is called content negotiation
Am I forced to receive a json response also?
No. The format of the data you send and the format of the data you receive are unrelated.
Or I can receive a html response instead?
You can.
the way that I will parse the response (to parse a json or not)
Read the Content-Type response header and use it to determine what format the data is in.
what Accept header to use
Ask for a data format that you:
are comfortable parsing and processing
know that server is able to send