express

npm init

npm install express

npm install nodemon

nodemon:开发时使用,代码更改时自动帮你重载

pm2:服务端使用,把node运行在后台

let express=require('express');
let app= express();
app.get('/',function (req,res) {
    res.send('hello express');
});

app.listen(3000);

运行:nodemon (入口文件叫server.js的时候后面不用加任何东西)

请求和响应

https://expressjs.com/en/4x/api.html#res

返回:可以是json或者数组

路由

https://expressjs.com/en/guide/routing.html

app.get('/profile/:id',function (req,res) {
    res.send("You requested to see a profile with the id of " +req.params.id);
});

服务端定义url是支持正则的

url query(取出用户提交的参数)

POST请求

npm install body-parser –save

//处理表单
const bodyParser=require('body-parser');
let app= express();
//app.use(bodyParser.json()); //添加中间件
let jsonParser=bodyParser.json(); //处理
let urlencodedParser=bodyParser.urlencoded({extended:false});
app.post('/',urlencodedParser,function (req,res) { //这里的urlencodedParser是一个中间件
    console.dir(req.body);
    res.send('ok');
});

文件上传

可以用multer包、fs包

http://javascript.ruanyifeng.com/nodejs/fs.html

https://github.com/expressjs/multer

const multer = require('multer');
const fs=require('fs')
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
});
var createFolder=function (folder) {
    try{
        fs.accessSync(folder);
    }catch (e) {
        fs.mkdirSync(folder)
    }
};
var upload = multer({storage:storage});
createFolder('./uploads/');
app.get('/form',function (req,res) {
    res.sendFile(__dirname+ '/index.html');
});
app.post('/upload',upload.single('logo'),function (req,res) {
    console.dir(req.file);
});

模板引擎

app.set('view engine','ejs');
app.get('/form',function (req,res) {
    let person=req.query.name;
    res.render('index',{person:person})
});

//index.ejs
<h1><%= person %></h1>
......

中间件

差不多就长这样吧👇

#app.use() 使用中间件


app.use(function (req,res,next) {
    console.log('first middleware');
    next();
    console.log('first middleware done')
});
app.use('/home',function (req,res,next) {
    console.log('second middleware');
    next();
});
app.get('/home',function (req,res) {
    res.send('ok');
});
app.listen(3000)

路由中间件

//./routers/index.js

const express=require('express');
const router=express.Router();

router.get('/',function (req,res,next) {
    res.send('root')
});

module.exports=router;


//./routers/users.js
const express=require('express');
const router=express.Router();

router.get('/',function (req,res,next) { //注意这里还是/不是/users
    res.send('users')
});

module.exports=router;

//server.js
let indexRouter=require('./routers/index');
let usersRouter=require('./routers/users');
app.use('/',indexRouter);
app.use('/users',usersRouter);

又水了一篇

发表评论

电子邮件地址不会被公开。 必填项已用*标注