我使用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;
}
任何想法,爲什麼在第一次請求空白的回報?
謝謝!