koa写服务器脚本无法读取css文件(待解决)

最近在跟着廖雪峰的教程学js的时候遇到的,有时无法读取到html 里的css文件

app.js:

const Koa = require('koa');
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const nunjucks = require('nunjucks');
const templating = require('./templating');
const staticFiles = require('./staticFiles');
const controller = require('./controller');
const app = new Koa();
const isProduction = process.env.NODE_ENV === 'production';


//import css file


app.use(async (ctx, next) => {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    var
        start = new Date().getTime(),
        execTime;
    await next();
    execTime = new Date().getTime() - start;
    ctx.response.set('X-Response-Time', `${execTime}ms`);
});

//这里读取静态文件和css
if (!isProduction){
    console.log('requiring static files');
    let staticFiles = require('./staticFiles');
    app.use(staticFiles('/static/',__dirname+'/static'));
}

app.use(bodyParser());


app.use(templating(__dirname+'/views',{//tocheck
    noCache:!isProduction,
    watch:!isProduction
}));

controller.readController(router); //redirect to static files if url contains static, or built in href in home page

app.use(router.routes());

app.listen(3000);
console.log('app started at port 3000');

staticFiles函数:

const path = require('path');
const mime = require('mime');
const fs = require('mz/fs');
//preprocess
//url:'/static/', dir: __dirname+'/static'
function staticFiles(url,dir){
    return async(ctx, next) => {
    	//取得请求的路径
        let rpath = ctx.request.path;
        console.log('checkpoint 1 ' +ctx.request.path);
        //check start with url, url = static
        //判断是否以/static/开头
        if (rpath.startsWith(url)){
            console.log('sticking address...',rpath);
            //得到文件绝对地址
            fp = path.join(dir, rpath.substring(url.length));
            console.log('checkpoint 2 '+ fp);
            //check existence of file
            console.log('check point 3 -----'+await fs.exists(fp));
            //判断文件是否存在
            if (await fs.exists(fp)){
                console.log('applying '+ fp);
                //服务器返回
                ctx.response.type = mime.lookup(rpath);//tocheck mime.lookup to mime.getType
                //read file and assign to response body
                ctx.response.body = await fs.readFile(fp);
                console.log('applied '+ fp);
            } else {
                // file not exist:
                ctx.response.status = 404;
            }
        } else {
            
            //turn to next middleware
            await next();
        }
    }
}

module.exports = staticFiles;

html文本:

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="description" content="learn javascript by www.liaoxuefeng.com">
    <title>{{ title }}</title>
    <script src="/static/js/bootstrap.js"></script>
    <link rel="stylesheet" href="/static/css/bootstrap.css">
    
</head>

加载之后无法应用css文件:
koa写服务器脚本无法读取css文件(待解决)_第1张图片

查看控制台输出:

D:\Program Files (x86)\nodejs\node.exe --inspect-brk=33024 app.js
Debugger listening on ws://127.0.0.1:33024/d917db8b-6709-47f9-9e9d-f58b4eef1989
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
requiring static files
processing controller: index.js
register URL mapping: GET /
register URL mapping: POST /signin
app started at port 3000
Process GET /...
checkpoint 1 /
push the login form
(node:12996) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated
Process GET /static/css/bootstrap.css...
checkpoint 1 /static/css/bootstrap.css
sticking address... /static/css/bootstrap.css
checkpoint 2 d:\Projects\Programming\javaScript\view-koa\static\css\bootstrap.css
//这里为什么就不读取了呢,连判断文件存在都没返回
Process GET /static/js/bootstrap.js...
checkpoint 1 /static/js/bootstrap.js
sticking address... /static/js/bootstrap.js
checkpoint 2 d:\Projects\Programming\javaScript\view-koa\static\js\bootstrap.js
check point 3 -----true
check point 3 -----true
applying d:\Projects\Programming\javaScript\view-koa\static\js\bootstrap.js
applying d:\Projects\Programming\javaScript\view-koa\static\js\bootstrap.js
applied d:\Projects\Programming\javaScript\view-koa\static\js\bootstrap.js
applied d:\Projects\Programming\javaScript\view-koa\static\js\bootstrap.js

(待解决)

你可能感兴趣的:(koa写服务器脚本无法读取css文件(待解决))