簡體   English   中英

koa.js 基本應用程序總是返回 Not Found

[英]koa.js basic app always returns Not Found

我正在嘗試編寫我的第一個 koa.js 應用程序,但由於某種原因,我無法使用函數設置路由。 我不斷收到“未找到”錯誤。

這是我的代碼 -

const koa    = require('koa'),
      router = require('koa-router')();

var app = new koa();

router.get('/', function *(next) {
    this.body = "Hello"
});

app
  .use(router.routes())
  .use(router.allowedMethods());

app.listen(3000);
console.log("Listening on port 3000");

此代碼基於 koa-router github 示例

然后當我去 localhost:3000 我得到“未找到” 在此處輸入圖像描述

我錯過了什么? 謝謝

現在函數生成器在 koa2 中已棄用。 使用的代碼如

const koa = require('koa'),
router = require('koa-router')();

var app = new koa();

router.get('/', function(ctx, next) {
 ctx.body = "Hello"
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000);
console.log("Listening on port 3000");

我遇到了同樣的錯誤,但我發現這可能是最簡單的方法。

'strict'
const koa = require('koa')
const app =new koa()
var route = require('koa-router');
const host = 'localhost' || '127.0.0.1';
const port = 3123 || process.env.PORT;

// initiate the route
var my_route = route();
// defines the route
my_route.get('/',function(body, next){
    body.body = "I love routes"
});
app.use(my_route.routes())
app.listen(port, host,(err)=>{
    if(err){
        throw err;
    }
    console.log("The server has started")
})

我知道這是舊的,但對於 koa 的新手來說,除了在 koa 3 中使用新方法之外,因為我有同樣的錯誤,因為很多文檔和示例讓我感到困惑,據說路線應該是最后一個使用的中間人但不是在設置路由之前,因此您應該在這樣的路由代碼設置器之前編寫使用路由中間件的行

const koa    = require('koa'),
      router = require('koa-router')();

var app = new koa();

app.use(router.routes())
  .use(router.allowedMethods());

router.get('/', function *(next) {
    this.body = "Hello"
});

app.listen(3000);
console.log("Listening on port 3000");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM