报Not Found/404的错误如果代码没写错,那就只有一个原因,路径没有写对。
我的结构目录为:
我想要访问static下的静态资源,即./static/app.js,贴上写的代码:
const Koa = require('koa');
const path = require('path')
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const serve = require('koa-static')
const staticPath = 'static'
const app = new Koa();
// log request URL:
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
await next();
});
app.use(serve(
path.join( __dirname,staticPath)
))
app.use(bodyParser());
app.listen(3000);
console.log('app started at port 3000...');
这里serve配的路径是( __dirname,staticPath),也就是./static,这样看起来没什么问题,用浏览器请求一下:
没想到以/static/app.js请求的时候却是Not Found,调试源码后发现请求的路径竟是:/static/static/app.js
由此看来koa-static是直接把/static/设成了根路径,因此我们直接请求资源的名字就好了:
总结:我们请求的路径应该为 koa-static设置的路径的相对路径