html - Router.get 用于在 koa 中渲染 index.HTML
问题描述
尝试router.get('/', async ctx => ctx.redirect('index.html'))
了初始路由,但失败了。
有没有其他方法可以重定向到 index.HTML / index.ejs router.get()
?
我是 Koa 的新手。请帮忙
解决方案
仅仅重定向是不够的。你需要告诉 koa 如何提供静态文件……这koa-static
是一个很好的包。
假设您将两个文件放入子目录中./public
- 索引.html
- redirect.html(也用于演示重定向)
然后做
npm install koa
npm install koa-static
您的代码基本上应该如下所示:
'use strict';
const koaStatic = require('koa-static');
const Koa = require('koa');
const app = new Koa();
// possible redirect middleware
const redirect = async function(ctx, next) {
if (ctx.request.url === '/') {
ctx.redirect('redirected.html')
} else {
await next()
}
}
app.use(redirect); // this will add your redirect middleware
app.use(koaStatic('./public')); // serving static files
app.listen(3000);
评论
- 如果您现在在浏览器中调用
localhost:3000/index.html
...您将获得以下内容index.html
- 如果你打电话
localhost:3000/
......你会得到的内容redirect.html
- 您实际上不需要重定向中间件(如上所示)。koa-static 将
/
调用重定向到index.html
推荐阅读
- r - 是否有一个函数可以知道一列有多少次具有最佳值?
- python - 如何从 PySide 中可能继承的 QLabel 样式中删除阴影?
- java - seqSearchFunction(String s,char c)
- c# - WebCamTexture 未在 3D 平面上呈现
- r - 将列值附加到另一列
- macros - 方案宏成对处理题
- java - 如何修复“错误:XML 文档结构必须在同一个实体内开始和结束”?
- outlook - loadCustomPropertiesAsync 方法在 Outlook for Android 上超时
- http - 使用 CORS 块端口
- javascript - 每次我在打字稿中编辑内容时刷新 .js 文件