Calling stored procedure from node js

故事扮演 提交于 2020-02-21 06:32:27

问题


I am using express and I am trying to call LoginMember stored procedure from Azure portal. This is my form from, taken from ejs:

<form method="post" action="/available-copies">
      <input type="text" placeholder="SSN" name="userssn">
      <input type="password" placeholder="Password" name="userpassword">
      <input type="submit" value="Login">
</form>

This is my post request

router.post('/available-copies', function (req, res) {
    var ssn = req.body.userssn;
    var password = req.body.userpassword;

    sql.connect(sqlConfig, function (err) {
        if (err) console.log(err);
        // create Request object
        var request = new sql.Request();
        // query to the database and execute procedure
        request.query("exec LoginMember @SSN='"+ssn+"', @PASSWORD='"+password+"';", function (err, recordset) {
            if (err) console.log(err);

            res.send(recordset);
        });
    });
    sql.close()
});

SqlConfig comes from another file and this part is fine. Just in case, this is my stored procedure creation code:

CREATE PROCEDURE LoginMember @SSN varchar(11), @PASSWORD char(64)
AS
BEGIN
   Select * from Member
   WHERE Member.ssn = @SSN AND Member.password = @PASSWORD
END

What happens- When I submit my form, page keeps loading for 3-5mins, after that I get

This page isn’t working
localhost didn’t send any data.

Console doesn't return any additional errors. I know this might be not the best solution I can be using, but this is my approach and I want to make it work.


回答1:


Make sure you are closing sql connection after query execution or failure.What i found in your code is that you are closing sql connection outside sql.connect which is incorrect because node js is asynchronous in nature which is killing your connection before completion.Please find the update code below:

router.post('/available-copies', function (req, res) {
var ssn = req.body.userssn;
var password = req.body.userpassword;

sql.connect(sqlConfig, function (err) {
    if (err) console.log(err);
    // create Request object
    var request = new sql.Request();
    // query to the database and execute procedure 
    let query = "exec LoginMember @SSN='" + ssn + "', @PASSWORD='" + password + "';";
    console.log(query)
    request.query(query, function (err, recordset) {
        if (err) {
            console.log(err);
            sql.close();
        }
        sql.close();
        res.send(recordset);

    });
  });
});

I hope it helps.



来源:https://stackoverflow.com/questions/50697134/calling-stored-procedure-from-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!