我使用koa作为休息后端,但是我无法使路由和请求/响应正常工作,当使用axios调用URL时,承诺失败。
server.js
const route = require('koa-route');
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
const path = require('path');
const bodyParser = require('koa-bodyparser');
const Datastore = require('nedb'),
db = new Datastore({
filename: __dirname +'/storage.db' ,
autoload: true
});
// something
app.use(bodyParser());
app.use(serve(__dirname + '/dist'));
app.use(route.get('/api/projects', async function (next) {
let projects = [];
await db.find({}, function (err, docs) {
projects = docs;
});
this.body = projects;
}));
const PORT = process.argv[2] || process.env.PORT || 3000;
app.listen(3000);
当我使用axios向/ api / projects发出请求时,我得到并清空数组
来自我的package.json
"scripts": {
"start": "nodemon server.js --exec babel-node --presets es2015,stage-2"
},
答案 0 :(得分:0)
你将承诺与回调混合在一起,这很可能会引发你的问题。
坚持使用承诺:
app.use(route.get('/api/projects', async function (next) {
let projects = await db.find({});
this.body = projects;
}));