koa2 + koa-router + mysql继续返回'未找到'

时间:2017-04-13 10:19:02

标签: node.js koa koa-router koa2

背景

我正在使用koa2和一些中间件来构建一个基本的api框架。但是当我使用" ctx.body"要在我的路由器中发送响应,客户端始终会收到" Not Found"

我的代码

./ app.js

string youtubeVideoID = "INSERT VIDEO ID"; // Set video id
YouTubeQuality youtubeQuality = YouTubeQuality.Quality720P; // Set video quality

YouTubeUri videoUri = await YouTube.GetVideoUriAsync(youtubeVideoID, youtubeQuality);

// You can get Uri using videoUri.Uri and set the source to a media player

./路由器/ gateway.js

const Koa = require('koa');
const app = new Koa();
const config = require('./config');

//Middlewares
const loggerAsync = require('./middleware/logger-async')
const bodyParser = require('koa-bodyparser')
const jsonp = require('koa-jsonp')
app.use(loggerAsync())
app.use(bodyParser())
app.use(jsonp());

//Router
const gateway = require('./router/gateway')
app.use(gateway.routes(), gateway.allowedMethods());

app.use(async(ctx, next) => {
    await next();
    ctx.response.body = {
        success: false,
        code: config.code_system,
        message: 'wrong path'
    }
});

app.listen(3000);

然后是一个db包装器(mysql)

./分贝/异步-db.js

/**
 * Created by Administrator on 2017/4/11.
 */
const Router = require('koa-router');
const gateway = new Router();
const df = require('../db/data-fetcher');
const config = require('../config');
const moment = require('moment');
const log4js = require('log4js');
// log4js.configure({
//     appenders: { cheese: { type: 'file', filename: 'cheese.log' } },
//     categories: { default: { appenders: ['cheese'], level: 'error' } }
// });
const logger = log4js.getLogger('cheese');
logger.setLevel('ERROR');


gateway.get('/gateway', async(ctx, next) => {
    let time = ctx.query.time;
    if (!time) {
        ctx.body = {
            success: false,
            code: config.code_system,
            message: 'Please input running times'
        }
    } else {
        try {
            let r = await df(`insert into gateway (g_time, g_result, g_date) values (${time}, '',now())`);
            return ctx.body = {
                success: true,
                code: config.code_success
            }
        } catch (error) {
            logger.error(error.message);
        }
    }
});

module.exports = gateway;

./分贝/数据fetcher.js

const mysql = require('mysql');
const config = require('../config');

const pool = mysql.createPool({
    host: config.database.HOST,
    user: config.database.USERNAME,
    password: config.database.PASSWORD,
    database: config.database.DATABASE
})

let query = (sql, values) => {
    return new Promise((resolve, reject) => {
        pool.getConnection(function (err, connection) {
            if (err) {
                reject(err)
            } else {
                connection.query(sql, values, (err, rows) => {

                    if (err) {
                        reject(err)
                    } else {
                        resolve(rows)
                    }
                    connection.release()
                })
            }
        })
    })
}

module.exports = query

我的运行结果

当我在端口3000上启动服务器然后通过http://localhost:3000/gateway?time=5访问时,它总是返回"未找到"。但正如我所见,我已经使用了

const query = require('./async-db')
async function performQuery(sql) {
    let dataList = await query(sql)
    return dataList
}

module.exports = performQuery;

发送回复。我调试并发现数据库处理完成得很好,新数据插入得很好。

当我删除该数据库插入行时,它运行良好并返回成功信息。

return ctx.body = {
                success: true,
                code: config.code_success
            }

有什么不对吗?

非常感谢!

更新2017/04/27

现在我发现了问题。这是由于我的自定义中间件

let r = await df(`insert into gateway (g_time, g_result, g_date) values (${time}, '',now())`);

代码如下 -

const loggerAsync = require('./middleware/logger-async')

我将其更改为异步/等待方式,然后一切正常。

有谁能告诉我这个中间件有什么问题?

2 个答案:

答案 0 :(得分:0)

我想,你的问题是./db/data-fetcher.js函数。当你打电话时

let r = await df(`insert ....`)

你的df - 函数应该返回一个承诺。

所以尝试像这样重写./db/data-fetcher.js(未经测试):

const query = require('./async-db')

function performQuery(sql) {
    return new Promise((resolve, reject) => {
        query(sql).then(
            result => {
                resolve(result)
            }
        )
    }
}

module.exports = performQuery;

希望有所帮助。

答案 1 :(得分:0)

正确的中间件:

function log( ctx ) {
    console.log( ctx.method, ctx.header.host + ctx.url )
}

module.exports = function () {
    return function ( ctx, next ) {
        log( ctx );
        return next()
    }
}

原因:涉及resolve时; promise chain was completed;响应已发送给客户。虽然中间件仍然存在,但响应已经消失了!

尝试理解It seems that if you want to use a common function as middleware, you have to return the next function

nodejs(koa):Can't set headers after they are sent