尝试运行节点index.js时未找到错误

时间:2018-09-15 12:58:37

标签: node.js

我已经安装了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时未找到错误。

我缺少什么东西了吗?

1 个答案:

答案 0 :(得分: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