Home > Web Front-end > JS Tutorial > body text

Detailed explanation of express's middleware bodyParser_node.js

WBOY
Release: 2016-05-16 16:29:07
Original
1787 people have browsed it

bodyParser is used to parse the content in the body requested by the client, and internally uses JSON encoding processing, url encoding processing and file upload processing.

The following is an example of file upload.

Create a 1.html page

Copy code The code is as follows:





Upload files to the server
                                                                      function uploadFile(){
          var formData=new FormData();
            var files=document.getElementById("files").files;
            var file=files[0];
             formData.append("myfile",file);
            var xhr=new XMLHttpRequest();
                xhr.open("post","index.html",true);
                  xhr.onload= function (e) {
If(this.status==200)
document.getElementById("result").innerHTML=this.response;
             };
                 xhr.send(formData);
         }



Please select a file:





The above XMLHttpRequest object and FormData object are the contents of HTML5 and will not be explained in detail. These two objects can be used to upload files selected by the user to the server.
After using the app.use(express.bodyParser()) middleware on the server side, the http.IncomingMessage requested by the client, that is, the res object has a files attribute.

server.js code:

Copy code The code is as follows:
var express=require("express");
var fs=require("fs");
var app=express();
app.use(express.bodyParser());
app.get("/index.html", function (req,res) {
res.sendfile(__dirname "/1.html");
});
app.post("/index.html", function (req,res) {
var file=req.files.myfile;
fs.readFile(file.path, function (err,data) {
             if(err) res.send("File reading operation failed");
         else{
                          fs.writeFile(file.name,data, function (err) {
If(err) res.send("File writing operation failed.");
                     else res.send("File uploaded successfully");
              })
         }
});
});


app.listen(1337,"127.0.0.1", function () {
console.log("Start monitoring");
});

After starting the server, run the browser:

Select file:

The message "Upload successful" appears on the browser,

The files we uploaded are also available on the server side.

After clicking upload:

In addition, bodyParse can accept json data submitted by client ajax and process url.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template