Express框架提供了配置路由的接口,这里在处理客户端发送来的请求有有四种,其中Get请求很平常,按照基本操作执行就可以了,当处理客户端发来的Post请求时,这就有了说法,有三种形式,[这里需要注意Post请求提交过了的如果时文件(图像)]
1. 'Content-Type':'multipart/form-data',body:formData
2.'Content-Type':'application/json',body:JSON.stringify({a:1})
3.'Content-Type':'application/x-www-form-urlencoded',body:'a=1&b=2&c=3'
参考资料如下:
1 body-parser中间件:https://www.npmjs.com/package/body-parser
2.multer中间件:https://github.com/expressjs/multer
3.静态文件服务器: http://www.expressjs.com.cn/starter/static-files.html
1 const express = require('express'); 2 3 const fs = require('fs'); 4 5 const bodyParser = require('body-parser'); 6 7 const multer = require('multer') 8 9 const app = express(); 10 11 //使用static中间件实现文件服务 12 app.use('/source',express.static('./public')); 13 14 //使用中间件处理提交的数据 15 //可以处理'Content-Type':'application/json', 16 //的body数据 17 app.use(bodyParser.json()); 18 19 //使用此中间件处理 20 //'Content-Type':'application/x-www-form-urlencoded' 21 app.use(bodyParser.urlencoded({ extended: false })) 22 23 //'Content-Type': 针对post请求是文件,这里any值得时接收所有的文件类型 24 app.use(multer().any()) 25 26 27 app.post('/api/postMessage',(request,response)=>{ 28 console.log(request.body); 29 console.log(request.files); 30 const image = request.files[0]; 31 const buffer = image.buffer; 32 const date = new Date(); 33 fs.writeFile(`./public/image/${date}.png`, buffer,(err)=>{ 34 if (err) { 35 console.log(err); 36 } else { 37 console.log('ok.'); 38 } 39 }); 40 response.json({ 41 success:true, 42 }) 43 })
1 //引入express框架 2 const express = require('express'); 3 4 //创建一个App 5 const app = express(); 6 7 //使用中间件 8 9 const bodyParser = require('body-parser'); 10 app.use(bodyParser.json()); 11 12 13 //配置请求路由 14 const login = require('./Login'); 15 app.post('/api/login',login); 16 17 //开启监听 18 const server = app.listen(3000, function () { 19 console.log('开启监听'); 20 });1 module.exports = (req,res)=>{ 2 console.log('收到请求'); 3 //req.body是app提交上来的数据 4 console.log(req.body); 5 if (req.body.name == req.body.pwd) { 6 const d = { 7 success:true, 8 data:{ 9 uid:1001, 10 token:'xxxx' 11 } 12 } 13 res.json(d); 14 } 15 else { 16 const d = { 17 success:false, 18 message:'密码错误', 19 } 20 res.json(d); 21 } 22 //是服务器需要返回给App的数据 23 }
未完待续...