安装express
npm i express
1.请求与响应
var express = require("express");
var bodyparser = require("body-parser");
var app = express();
app.use(bodyparser.urlencoded({extended:false}));
// app.get("/",function(request,response){
// response.send("test"+request.query.id);
// })
// app.get("/detail/:id",function(request,response){
// response.send("test"+request.params.id);
// })
app.post("/",function(request,response){
response.send("Hello POST");
})
app.listen(20000);
console.log("Server start on 127.0.0.1:20000");
2.文件上传
npm i --save multer
var express = require("express");
var bodyparser = require("body-parser");
var multer = require("multer");
var upload = multer({dest:"uploads/"});
var app = express();
app.use(bodyparser.urlencoded({extended:false}));
// 这里的avatar就是使用post请求方式时参数
app.post("/upload",upload.single('avatar'), function(request,response){
response.send("upload success");
})
app.listen(20000);
console.log("Server start on 127.0.0.1:20000");
可指定文件存储地址以及文件名:
var express = require("express");
var bodyparser = require("body-parser");
var fs = require("fs");
var multer = require("multer");
var upload = multer({
storage: multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./uploads")
},
filename: function (req, file, callback) {
callback(null, file.originalname)
}
})
});
var app = express();
app.use(bodyparser.urlencoded({
extended: false
}));
网友评论