I have been messing around with express js for a while now and I have come across something called body parser. According to my research body parser allows us to POST content form our HTTP request.
My question that, is it absolutely necessary to use body parser when using express.js?
If it is not necessary then what are the advantages of using it and if body parser is not used then what needs to be done to make sure that the content is POSTED?
Thank you in advance.
Let’s try to keep this least technical.
Let’s say you are sending a html form data to node-js server i.e. you made a request to the server. The server file would receive your request under a request object. Now by logic, if you console log this request object in your server file you should see your form data some where in it, which could be extracted then, but whoa ! you actually don’t !
So, where is our data ? How will we extract it if its not only present in my request.
Simple explanation to this is http sends your form data in bits and pieces which are intended to get assembled as they reach their destination. So how would you extract your data. Use something called “body-parser” which would do this for you.
body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need. First of all require the following in your app.js file.
var bodyParser = require('body-parser')
and add the following line to make it work
app.use(bodyParser.urlencoded({extended: true}));
You can make use of the events on('data') and on('end') to extract the payload. Whenever a POST request is sent, data arrives as a stream of bits. When the stream comes in the on('data') event is fired, and you can start collecting the stream into a buffer. When the stream ends (all the data has been received) the on('end') event is fired, that is when you can start using the data that you just collected.
Yopu need to include stringDecoder (stringDecoder is a module that comes built into node)
const string_decoder= require('string_decoder').StringDecoder;
You need to have this piece of code running as middleware.
var buffer= "";
request.on('data', function(data_stream)
{
//start collecting the data stream into a buffer
buffer= buffer + utf8_decoder.write(data_stream);
});
request.on('end', function()
{
buffer= buffer + utf8_decoder.end();
//add the buffer to the request object so it can be accessed elsewhere
request.payload= buffer;
});
This is probably the best way if you decide not to use any external libraries.
Related
I am trying to parse my csv file in server and return back the information after parsing and analyzing the data in csv.
I am not that used to express and i dont know any view engine.
I plan to use
res.sendFile(path.join(__dirname, "/index.html"));
to host my index file.
What are the other way than ajax and view template that can I send data to the index.html with sendFile.
I am sending JSON files from server to client
Any kind of help is appreciated !!!
When a client (such as a browser) makes a request you can respond with one thing.
You can respond with:
The contents of a file as you are now (although you should use the static middleware instead of rolling your own end point handlers (without caching) one-by-one)
A template + some data rendered into a single file (using the view engines you haven't gotten around to learning yet)
Some JSON (typically in response to an Ajax request so the a JS program running in an HTML document get add more data to the existing HTML page)
Something else
If sending an unmodified file is not what you want, then don't use sendFile.
I understand that fetch() response lets you receive formData from a server. I searched for an example that implements this functionality but I didn't find a single one. All examples talk about uploading (posting) formData from a client to a server, but not vice versa. This doesn't explain the .formData() method of the response.
So, could you please direct me to any link that has an example that receives a form data from a PHP server using the .formData() method of a fetch() response.
Thank you
https://developer.mozilla.org/en-US/docs/Web/API/Body/formData demonstrates the basic idea:
response.formData()
.then(function(formdata) {
// do something with your formdata
});
But it's very unusual for a server to return data in formData format - I've never seen that happen. It's not actually a very convenient format when it's serialised. Normally a server will return plain text, HTML, JSON or XML (or binary file data, of course).
The "note" in yellow at the top of the documentation explains what it's mainly used for. It says:
This is mainly relevant to service workers. If a user submits a form
and a service worker intercepts the request, you could for example
call formData() on it to obtain a key-value map, modify some fields,
then send the form onwards to the server (or use it locally).
(It's important to realise that this can read from the body of an outgoing request as as well as an incoming response. And also that the comparable text(), json() blob() etc methods can all be used in both directions too - these methods are attached to the Body object. Both requests and responses can contain a Body. So actually these methods don't care if it's a request or a response, they simply try to read from the Body of whatever it happens to be.)
I just started watching some node tutorials and I wanted help understanding the response and request streams that I get from http.createServer(). Response & Request are streams, so does that mean than Node.js sends and recieves data in chunks?
For example, if I called
res.write("test1");
res.write("test2");
res.end();
would it only write both those things when I call end() or would it flush to the stream and send to the client making the request as and when I call write()?
Another example to elaborate on my question is if I had a txt file with a lot of plaintext data, then I setup a read stream that pipes data from that file to the res object would it pipe that data in chunks or do it once everything is in the buffer.
I guess my question also applies to the request object. For instance, is the body of the request built up packet by packet and streamed to the server or is it all sent at once, and node just chooses to make us use a stream to access it.
Thanks alot!
The first time response.write() is called, it will send the buffered header information and the first chunk of the body to the client. The second time response.write() is called, Node.js assumes data will be streamed, and sends the new data separately. That is, the response is buffered up to the first chunk of the body.
full foc
So basically, if you .write() a small piece of data, it may be buffered until theres a complete chunk or .end() is called. If .write() already has the size of a chunk, it will be transmitted immeadiately.
I have ButtonClick.js and TakeData.js files. I defined my json data in TakeData.js as below
var dataObj = {};
var locationsObj = "locations";
dataObj[locationsObj] = {};
dataObj[locationsObj].source = [];
dataObj[locationsObj].target = [];
When I click the button in ButtonClick.js and the code snippet as below
button()
.container(g2)
.text(text2)
.count(1)
.cb(function()
{
console.log(dataObj[locationsObj].source[0]);
console.log(dataObj[locationsObj].source[1]);
console.log(dataObj[locationsObj].target[0]);
console.log(dataObj[locationsObj].target[1]);
console.log("SaveFile");
})();
I want to send json data into the nodejs file writing function as the following.
fs.writeFile('sample.txt', [need to insert my JSON], function(err) {
if(err) return console.log(err);
console.log('Hello JSON > sample.txt');
});
How can I do that? Is there another effective way?
Your backend needs to have an HTTP server listening on some port that is accessible to your frontend. Then your frontend needs to make an AJAX request to your backend (most likely a POST request) and send the required data in the request body.
Now, your backend needs to handle the request, get the data and write it to the file or do whatever you want with that.
Things to keep in mind:
use body-parser if you're using Express
remember about CORS
It's easier if you use a higher level framework on the backend like Express, Hapi, Restify, LoopBack etc. instead of the low level http module in Node.
It's also easier if you use a framework on the frontend like jQuery, Angular, React, Aurelia, Ember etc.
The first step is to set up a RESTful POST operation (an HTTP POST) on your server. This is the typical service mechanism for what is sometimes called an AJAX call. Once you have the server set up to receive a string via the POST, you can serialize your objects on the client side and deserialize (reconstitute) the objects on the server side.
To serialize, you can use stringify on the client side. A simple web search for "stringify" will show you different ways to use stringify in a browser-independent, backward compatible way.
stringify(obj)
On the server side, node.js has a global JSON object. Use parse to reconstitute an object or objects from the string. Other major languages now have similar parser methods. 1
JSON.parse(strJSON)
To get started, you can test the mechanism with just one simple object. Then you can aggregate the objects in a JSON array or associative array and send them all at once in a single POST.
[1] There are frameworks that encapsulate this process, but it may be of value to you to NOT initially use them so you get a clear picture of the mechanics of a RESTful POST over the HTTP protocol. It is the key thing that a browser does when you submit an HTML form, and RESTful operations are key communications elements in today's IT world.
I am developing a service using node.js, which returns a url to a file stored in my service's database. In my program, I save the file to, for example, "./aFolder/filename.jpg". I'm going to use DigitalOcean.
My questions are:
1. What is the form of such a url?
2. How can I get that url in my code using node.js?
Thank you in advance.
The URL will be whatever you want to make it since you'll presumably be the one writing the code to handle incoming requests.
Something like http://uri/download/aFolder/filename.jpg seems like a reasonable choice, but you'd need to write your app to accept those paths.
You may want to look into Express where you can add route handlers via app.route() such that anything to /download gets processed by a particular callback that facilitates the mapping of the URL onto your filesystem and will likely be sending the correct file over using res.download()
A basic skeleton might be:
app.route('/download:path')
.all(function(req, res, next) {
res.download(req.params.path)
})