我试图用Koa(v2)服务于前端。最终,我想使用React。但就目前而言,我只想尝试提供简单的html文件。
应用程序/ index.html的
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
server.js
import 'babel-polyfill';
import koa from 'koa';
import koaRouter from 'koa-router';
import serve from 'koa-static';
import mount from 'koa-mount';
const app = new koa();
const router = new router({ prefix: '/koa' });
// This route works
router.get('/', async (ctx) => {
ctx.body = 'Hello from Koa!';
});
app.use(router.routes());
const front = new koa();
// This route doesn't work.
front.use(serve(__dirname + '/app'));
// However, this will work, so then, I'm not using koa-serve correctly?
// front.use(async (ctx) => {
// ctx.body = "Mount this.";
// });
app.use(mount('/', front));
app.listen(3000);
那我该如何为前端服务?
答案 0 :(得分:1)
我使用了类似的代码,它对我有用,很奇怪,几乎就像你的例子一样,只是因为我没有使用异步
const koa = require('koa');
const koaRouter = require('koa-router');
const mount = require('koa-mount');
const serve = require('koa-static');
const app = new koa();
const router = new koaRouter({ prefix: '/koa' });
router.get('/', function *() {
this.body = 'Hello from Koa!';
});
app.use(router.routes());
const front = new koa();
front.use(serve(__dirname + '/app'));
app.use(mount('/', front));
app.listen(3000);
尝试使用koa-sendfile,只是为了测试它。我在下面有其他例子
请注意,我使用 koa-route ,而非 koa-router ,例如
此外,还有一个名为&#34; app&#34;的文件夹。包含&#34; index.html&#34;
'use strict';
const koa = require('koa');
const router = require('koa-route');
const mount = require('koa-mount');
const sendfile = require('koa-sendfile');
const serve = require('koa-static');
const app = koa();
const ui = koa();
const api = koa();
// API Mount
function *apiCall() {
this.body='response from api';
}
api.use(router.get('/', apiCall));
// UI Mount
// you have 2 ways:
// // 1. Using koa-sendfile
// function *serveIndex() {
// this.body='response from ui';
// yield sendfile(this, __dirname + '/app/index.html');
// if (!this.status) this.throw(404);
// }
// ui.use(serveIndex);
// 2. Using koa-static
ui.use(serve('app'));
app.use(mount('/api', api));
app.use(mount('/', ui));
app.listen(3000);