node.js - koa框架中引入koa-chche-control插件响应头不起作用
阿神
阿神 2017-04-17 14:54:36
0
1
548
var send = require('koa-send');
var Koa = require('koa');
var app = new Koa();
var Router = require('koa-router');
var cors = require('koa-cors');
var koaBody = require('koa-body')();
var cacheControl = require('koa-cache-control');
var router = new Router({
    prefix: '/public'
});
app.use(gzip());
app.use(cors())
    .use(router.routes())
    .use(router.allowedMethods());
    **app.use(cacheControl({
    maxAge: 500
}));**
router.get('/:fname/:cname', koaBody, function*() {
    var fname = this.params.fname;
    var cname = this.params.cname;
    console.log("文件类型" + fname);
    console.log("文件名" + cname);
    yield send(this, "./public/" + fname + "/" + cname);
})

var port = 8003;
app.listen(port);
console.log(` 启动成功,端口: ${port}`);

FireBug返回如下
返回头,maxAge=0;
ccess-Control-Allow-Methods →GET,HEAD,PUT,POST,DELETE
Access-Control-Allow-Origin →*
Cache-Control →max-age=0
Connection →keep-alive
Content-Type →image/jpeg
Date →Thu, 22 Sep 2016 08:02:04 GMT
Last-Modified →Wed, 14 Sep 2016 07:42:52 GMT
Transfer-Encoding →chunked
content-encoding →gzip
不知道为何设置了max-age到测试时还是没有显示出来、
附上插件地址https://github.com/DaMouse404...,小白请指教

阿神
阿神

闭关修行中......

Antworte allen(1)
洪涛

因为你中间件的位置位置放到路由的后面了,根本就没到cache-control。 放到前面就好了,修改如下

var send = require('koa-send');
var Koa = require('koa');
var app = new Koa();
var Router = require('koa-router');
var cors = require('koa-cors');
var koaBody = require('koa-body')();
var cacheControl = require('koa-cache-control');
var router = new Router({
    prefix: '/public'
});
app.use(gzip());
// put the middleware before your routers
app.use(cacheControl({
    maxAge: 500
}));
app.use(cors())
    .use(router.routes())
    .use(router.allowedMethods());
router.get('/:fname/:cname', koaBody, function*() {
    var fname = this.params.fname;
    var cname = this.params.cname;
    console.log("文件类型" + fname);
    console.log("文件名" + cname);
    yield send(this, "./public/" + fname + "/" + cname);
})

var port = 8003;
app.listen(port);
console.log(` 启动成功,端口: ${port}`);
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage