我使用express,body-parser和mysql设置node.js api。node.js - 第一个请求返回空白,第二个请求返回数据
每当我第一次获得路线请求时,我都会得到一个空白回报。如果我再次点燃它,我会得到理想的回报。
这是基本的设置...
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// include the model
var Tasks = require('./models/tasks.js');
// configure api to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
//console.log(req)
next(); // make sure we go to the next routes and don't stop here
});
router.route('/tasks')
// on routes that end in /tasks/:task_id
// ----------------------------------------------------
router.route('/tasks/:task_id')
// get the task by id (accessed as GET)
.get(function(req, res) {
Tasks.setProjectId(req.params.task_id);
Tasks.setResult(req.params.task_id);
var tasks = Tasks.getTasksByProjectId();
res.json(tasks);
});
app.use('/v1', router);
// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);
,这里是tasks.js
// include the db
require('../db.js');
var project_id, result;
module.exports.setProjectId = function(pid) {
project_id = pid;
}
module.exports.setResult = function(pid) {
//connection.connect();
connection.query('SELECT * FROM tasks WHERE project_id = ' + pid, function(err, rows, fields) {
if (err) throw err;
result = rows;
});
//connection.end();
}
module.exports.getTasksByProjectId = function(){
return result;
}
任何想法,为什么在第一次请求空白的回报?
谢谢!