首页 > 网站 > WEB开发 > 正文

node的express中间件之bodyParser

2024-04-27 14:16:16
字体:
来源:转载
供稿:网友

node的exPRess中间件之bodyParser

Posted on 2014-11-25 21:40 思思博士 阅读(...) 评论(...) 编辑 收藏

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

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

建立一个1.html页面

 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4     <meta charset="UTF-8"> 5     <title>向服务器上传文件</title> 6     <script type="text/javascript">         7         function uploadFile(){ 8             var formData=new FormData(); 9             var files=document.getElementById("files").files;10             var file=files[0];11             formData.append("myfile",file);12             var xhr=new xmlHttpRequest();13             xhr.open("post","index.html",true);14             xhr.onload= function (e) {15                 if(this.status==200)16                     document.getElementById("result").innerHTML=this.response;17             };18             xhr.send(formData);19         }20     </script>21 </head>22 <body>23 请选择文件:<input type="file" id="files" name="file" />24 <input type="button" value="上传文件" onclick="uploadFile();" />25 <div id="result"></div>26 </body>27 </html>

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

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

server.js端代码:

 1 var express=require("express"); 2 var fs=require("fs"); 3 var app=express(); 4 app.use(express.bodyParser()); 5 app.get("/index.html", function (req,res) { 6     res.sendfile(__dirname+"/1.html"); 7 }); 8 app.post("/index.html", function (req,res) { 9     var file=req.files.myfile;10     fs.readFile(file.path, function (err,data) {11         if(err) res.send("读文件操作失败");12         else{13             fs.writeFile(file.name,data, function (err) {14                 if(err) res.send("写文件操作失败.");15                 else res.send("文件上传成功");16             })17         }18     });19 });20 21 22 app.listen(1337,"127.0.0.1", function () {23     console.log("开始监听");24 });

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

QQiTJyZzOzgI9mxNqaMMhtIMokWDlmSbPkAgggNGIVWaXk2IDSPvmf/ON2Xa9/bt29zkVd+Hy29nP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GCIAiCyMojJ2uKIAiCqARlFEEQRBMoowiCIJpAGUUQBNEEyiiCIIgmUEYRBEE0gTKKIAiiCZRRBEEQTQR8NAki5vjx4w6HY3h4eLorEpzw8PCUlJSXX355uiuCTDOzyGlVMmN9G7/FFJwjb75pCA//6U9/umDBgumuS3A6Ozvff/999/Dw66+9Nt11QaaN2eW0KpkJvh3wPfWhwt7aNCn2oRY1sbxSy5Cu29nR8dprr5lMpsHBwZBrOeXExcU999xzb7755nR

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表