2016-06-29 61 views
2

我正在嘗試爲Koa(v2)提供前端服務。最終,我想使用React。但現在,我只是試圖提供一個簡單的HTML文件。如何與koa一起服務前端?

應用/ 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); 

那麼,如何服務於前端?

回答

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路線,不KOA路由器像其他例如

而且也有一個叫做「應用程序」包含的文件夾「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); 
相關問題