node.js - 如何用koa服务前端?

标签 node.js frontend koa

我正在尝试使用 Koa (v2) 提供前端服务。最终,我想使用 React。但现在,我只是尝试提供一个简单的 html 文件。

应用程序/index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>

服务器.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);

那么我该如何服务前端呢?

最佳答案

我使用了类似的代码,它对我有用,很奇怪,几乎像你的例子,只是我没有使用异步

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

此外,还有一个名为“app”的文件夹,其中包含“index.html”

'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);

关于node.js - 如何用koa服务前端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38089493/

相关文章:

javascript - 如何使用node.js从cloudinary下载图像

Javascript 输入字段应在键入时附加到 div 中

javascript - 在检查电子邮件输入验证后,如何使用我的按钮将用户重定向到另一个 HTML 页面?

node.js - 使用 Mongoose 在 Koa 中从流式查询中编写流式响应

node.js - PassportJS 在用户通过身份验证后不重定向

node.js - 如何使用 emscripten 通过 node.js 进行文件输入?

node.js - 使用 nginx 和 socket.io 时客户端无法一起交互

testing - 前端测试-工具Selenium RC

typescript - Koa + typescript : Property 'body' does not exist on type Request

javascript - Koa-异步函数错误处理内的异步函数