Home  >  Article  >  Web Front-end  >  express的中间件bodyParser详解_node.js

express的中间件bodyParser详解_node.js

WBOY
WBOYOriginal
2016-05-16 16:29:071696browse

bodyParser用于解析客户端请求的body中的内容,内部使用JSON编码处理,url编码处理以及对于文件的上传处理.

下面是一个文件上传的例子.

建立一个1.html页面

复制代码 代码如下:

 
 
 
    
     向服务器上传文件
    
 
 
 请选择文件:
 
 

 
 

上面的XMLHttpRequest对象与FormData对象时HTML5中的内容,不作重点讲解.用这两个对象可以将用户选取的文件上传到服务器端,.

在服务器端使用了app.use(express.bodyParser())中间件之后,代表客户端请求的http.IncomingMessage,也就是res对象就具有了一个files属性.

server.js端代码:

复制代码 代码如下:

 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("读文件操作失败");
         else{
             fs.writeFile(file.name,data, function (err) {
                 if(err) res.send("写文件操作失败.");
                 else res.send("文件上传成功");
             })
         }
     });
 });
 
 
 app.listen(1337,"127.0.0.1", function () {
     console.log("开始监听");
 });

启动服务器后,运行浏览器:

选择文件:

在浏览器端出现了 上传成功字样,

在服务器端也有了我们上传的文件.

点击上传后:

另外bodyParse可以接受客户端ajax提交的json数据,以及url的处理.

Statement:
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