尝试运行node index.js时出现“未找到错误”

3
我已安装了Node.js,现在想运行一些模拟API。 index.js:
const app = require('koa')()
const cors = require('koa-cors')
const logger = require('koa-logger')
const router = require('koa-router')()

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
}

function getRandomDeliveryLocation() {
    let locs = [
        { lat: 22.319181, lng: 114.170008, address: 'Mong Kok' },
        { lat: 22.336093, lng: 114.155288, address: 'Cheung Sha Wan' },
        { lat: 22.335538, lng: 114.176169, address: 'Kowloon Tong' }
    ]

    return locs[ getRandomInt( 0, locs.length ) ]
}

function getRandomDeliveryDescription( index ) {
    if ( index % 3 === 0 ) {
        return 'Deliver documents to Andrio'
    }

    let desp = [
        'Deliver documents to Andrio',
        'Gift pets to Leviero',
        'Gift pets to Alan'
    ]
    return desp[ getRandomInt( 0, desp.length ) ]
}

function getRandomDeliveryItem( index ) {
    return {
            id: index,
            description: getRandomDeliveryDescription( index ),
            imageUrl: 'https://s3-ap-southeast-1.amazonaws.com/lalamove-mock-api/images/pet-'
+ getRandomInt( 0, 9 ) + '.jpeg',
            location: getRandomDeliveryLocation()
    }
}

function delay(sec) {
    return new Promise(r => setTimeout(r, sec * 1000))
}

router.get('/pets', function* () {

    let cap = 70
    let offset = parseInt( this.query.offset, 10 )
    let limit = parseInt( this.query.limit, 10 )
    if ( isNaN( offset ) || isNaN( limit ) || offset < 0 || limit < 0 ) {
        this.status = 400
        return
    }

    yield delay(getRandomInt(0, 5))
    if (!getRandomInt(0, 9)) {
        this.status = 500
        return
    }

    this.body = []
    for ( let i = offset; i < offset + limit && i < cap; i++ ) {
        this.body.push( getRandomDeliveryItem( i ) )
    }

})

app
    .use(logger())
    .use(cors())
    .use(router.routes())
    .use(router.allowedMethods())

app.listen(8080)
console.log('Mock server started at port 8080')

我得到的是:

在打开 localhost:8080/pets 时出现了未找到错误。

我是否遗漏了什么内容?请问如何解决?


请确认一下,您在路由定义中是否有意使用了generator function - planet_hunter
@planet_hunter 是的,可以获取随机项目。 - Jhon
1个回答

1
你可以使用async/await代替生成器函数,这与您发布的代码相匹配。以下是示例代码(我进行了额外更改以修复其他问题):
router.get('/pets', async function (ctx) {
    let cap = 70
    let offset = parseInt( ctx.request.query.offset, 10 )
    let limit = parseInt( ctx.request.query.limit, 10 )
    if ( isNaN( offset ) || isNaN( limit ) || offset < 0 || limit < 0 ) {
        ctx.response.status = 400
        return
    }

    await delay(getRandomInt(0, 5))
    if (!getRandomInt(0, 9)) {
        ctx.response.status = 500
        return
    }

    ctx.response.body = []
    for ( let i = offset; i < offset + limit && i < cap; i++ ) {
        ctx.response.body.push( getRandomDeliveryItem( i ) )
    }
})

这里的更改包括:
  1. function *中删除*,以防止它成为生成器函数。
  2. 更改为async function,以便可以使用await
  3. 使用await代替yield等待你的delay承诺解决。
  4. this.query切换到ctx.request.query
  5. this.statusthis.body切换到ctx.response.statusctx.response.body

你是Node.js的专家。你能否解释一下出了什么问题? - Jhon
很抱歉让你等那么久,我在修改过程中进行了一些编辑,因为我打了几个错别字,这让你很难跟上。主要问题是你使用了一个生成器函数,而不是一个返回 Promise 的函数或者 async/await 函数。之后,你使用了 this,但它并没有引用该函数内的任何内容。这就是为什么我们必须使用 ctx,它具有 requestresponse 属性的原因。 - Kirk Larkin
大家看一下这个仓库,我刚刚复制了这个答案并在那里工作。希望它能有所帮助。https://repl.it/@ManojChalode/IndelibleFrayedBsddaemon 工作链接-https://indeliblefrayedbsddaemon--manojchalode.repl.co/pets?limit=10&offset=0 - planet_hunter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接