node学习(二) —— express框架(url路由和错误404自定义)

1.根据url  进行不同的操作 (路由和读文件,都图片)  
const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');


//设置静态路径  为当前路径
app.use(express.static(path.join(__dirname)));
app.get('/image/img', function(req, res,next) {
    res.writeHead(200,{'Content-Type':'image/jpeg'});
    fs.readFile('./logo1.jpg','binary',function(err,data){
        if(err){
            res.send(err);
            throw err;
        }else {
            res.write(data,'binary');
            res.end();
        }
        res.end(data);
    });
});
//这里path还可以写成带参数的

app.get('/index/index',function (req,res,next) {
    //加载页面
    res.writeHead(200,{'Content-Type':'text/html'});
    fs.readFile('./index/index.html','utf-8',function(err,data){
        if(err){
            next();
            throw err ;
        }
        res.end(data);
    });
});
//url /user/12
app.get('/user/:id', function(req, res){
    res.send('viewing ' + req.params.id);
});
//url /user/12/edit
app.get('/user/:id/edit', function(req, res){
    res.send('editing ' + req.params);
});
2.错误处理  404 自定义
//错误处理
app.get('*',function (req,res) {
    res.send('404 not found',404);
});

app.all('/user/:id/:op?', function(req, res, next){
    /***
     *   app.all()函数可以匹配所有的HTTP动词,也就是说它可以过滤所有路径的请求,
     *   如果使用all函数定义中间件,那么就相当于所有请求都必须先通过此该中间件。
     *   我们可以理解成  所有http相关的(并且路径匹配)都会经过这里
     *   这里如果路径写成*那么就匹配了所有啦   可以*配合同意添加头部 res.writeHead();
     */
});
app.listen(3000, () => console.log('Example app listening on port 3000!'));

猜你喜欢

转载自blog.csdn.net/wangshang1320/article/details/86074680