如何将函数调用值存储到变量node.js中
我正在创建一个node.js应用程序,它将查看传递给它的URL,然后返回正确的数据库连接字符串。下面是我的genericServer.js文件。第二个代码块是我的Connection.js文件。在URL中将id传递到genericServer文件时,我会将其传递给中间件connection.getConnString如何将函数调用值存储到变量node.js中,node.js,express,Node.js,Express,我正在创建一个node.js应用程序,它将查看传递给它的URL,然后返回正确的数据库连接字符串。下面是我的genericServer.js文件。第二个代码块是我的Connection.js文件。在URL中将id传递到genericServer文件时,我会将其传递给中间件connection.getConnString var express = require('express'); var connection = require('./connection'); var connStrin
var express = require('express');
var connection = require('./connection');
var connString = "";
var app = express();
app.get('/connectionString/:id', connection.getConnString, function(res){
res.on('response', function(response) {
res.on('data', function(chunk) {
connString += chunk;
console.log("The connection String is: " + connString);
});
});
});
app.listen(3333);
到目前为止,下面的代码确实返回了正确的连接信息,但我需要将此数据存储在(genericserver.js)服务器级别的变量中。我认为在调用connection.GetConnString中间件之后,我可以使用函数(res)捕获genericServer.js中的响应。到目前为止,似乎中间件处理并发回响应,但随后对函数(res){}的回调从未发生
关于如何在仍然使用app.get()的情况下将connection.getConnString响应存储到genericServer调用中的变量中,有什么想法吗
}) 使用响应传递数据不是一个好办法。在中间件中,可以将连接字符串设置为
req
的属性:
接下来将调用路由处理程序,您可以访问其中的属性:
app.get('/connectionString/:id', connection.getConnString, function(req, res) {
console.log("The connection String is: ", req.connectionString);
res.send(req.connectionString);
});
exports.getConnString = function(req, res, next) {
sql.query(..., function(err, results) {
... // get the connection string as per your code
req.connectionString = connectionString;
next(); // call the next middleware/route
});
};
app.get('/connectionString/:id', connection.getConnString, function(req, res) {
console.log("The connection String is: ", req.connectionString);
res.send(req.connectionString);
});