[英]How to return a value from a JS function and send it to another JS script in Node js?
我試圖從節點js中的js函數獲取返回值,並在我的服務器文件中的post方法中返回值。 但出於某種原因,我一直沒有定義。 我可能做錯了什么?我的目標是將記錄變量返回到我的server.js文件這是我到目前為止所嘗試的: -
sqlconfig.js
var sql = require('mssql');
var config = {
user: 'realm',
password: 'friend',
server: '123.45.67.89\\SQL2014',
database: 'ArtCaffee'
};
module.exports = {
sqlconnecttodb: function() {
sql.connect(config, function(err) {
if (err) console.log("message is for" + err);
});
},
updateMember: function(Country, BankName, Password, PublicIP, UserID) {
sql.connect(config, function(err) {
if (err) console.log("message is for" + err);
new sql.Request()
.input('Country', sql.VarChar(50), Country)
.input('BankName', sql.VarChar(50), BankName)
.input('Password', sql.VarChar(50), Password)
.input('PublicIP', sql.VarChar(50), PublicIP)
.input('UserID', sql.VarChar(50), UserID)
.execute('p_LoginUser').then(function(result) {
var records = result[0];
return records;
}).catch(function(err) {
console.dir(err);
});
});
}
};
Server.js
var cnn = require('./sqlconfig.js');
var express = require('express');
var app = express();
const bodyParser = require('body-parser');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
res.render('pages/index.ejs');
});
app.post('/', function(req, res) {
console.log({
username: req.body.uname
});
console.log({
password: req.body.upass
});
var r = cnn.updateMember("Kenya", "Artcaffe Nairobi", "admin1234", "127.0.0.1", "admin2");
console.log(r); // The value of r is still undefined
});
修改updateMember
函數:
updateMember: function(Country, BankName, Password, PublicIP, UserID, callback) {
sql.connect(config, function(err) {
if (err) console.log("message is for" + err);
new sql.Request()
.input('Country', sql.VarChar(50), Country)
.input('BankName', sql.VarChar(50), BankName)
.input('Password', sql.VarChar(50), Password)
.input('PublicIP', sql.VarChar(50), PublicIP)
.input('UserID', sql.VarChar(50), UserID)
.execute('p_LoginUser').then(function(result) {
var records = result[0];
// return records;
callback.call(this, null, records); // send back result
}).catch(function(err) {
console.dir(err);
callback.call(this, err); // send back error
});
});
}
然后,在server.js
您可以調用此函數:
cnn.updateMember("Kenya", "Artcaffe Nairobi", "admin1234", "127.0.0.1", "admin2", function (err, result) {
// process result here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.