美文网首页
Node.js框架Express学习

Node.js框架Express学习

作者: 二营长家的张大炮 | 来源:发表于2019-10-16 16:58 被阅读0次

    安装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
    }));
    

    相关文章

      网友评论

          本文标题:Node.js框架Express学习

          本文链接:https://www.haomeiwen.com/subject/lcsumctx.html