NodeJs,connection.query中的if语句

时间:2019-11-07 10:35:37

标签: javascript mysql node.js

我是一个C#家伙,试图使用React,Node和mysql创建一个登录页面。我怀疑我可以在连接。查询中写'if语句'吗?以下是我正在使用的代码段。当我尝试运行此脚本时,出现代理错误。

app.post('/api/world', (req, res) => {
 try{
  console.log(req.body);
  uname = req.body.post;

  var DBuserCheck = "SELECT EXISTS (SELECT * FROM `loginschema`.credentials WHERE uname =" + '"' + uname + '"' + ")";
  var DBpwdCheck = "SELECT pwd FROM `loginschema`.credentials WHERE uname =" + '"' + uname + '"';

connection.query(DBuserCheck, function(err,data){
if(DBuserCheck){
  connection.query(DBpwdCheck, function(err, pdata){
    if(pdata == req.body.password){
      res.json({Successfully_loggedin});
    }
    (err)? res.send(err) : res.json({pwdData_Wrong_Password: pdata});
    console.log('enter valid credentials');        
  });
}
(err) ? res.send(err) : res.json({ USERdata: data });
console.log('user query data: dataSTR',+data +" ; req string "+ req.body.post +"; uname string "+ uname);

 });
}
catch(ex){
  console.log('Message from Catch is ----->>>> '+ex);
}

});

我的代码是否正确,或者我必须执行其他任何步骤。我的代码首先正确运行,然后在结尾崩溃。我收到以下错误。

PS H:\PyProjects\login\loginproj> yarn dev
yarn run v1.17.3
$ concurrently --kill-others-on-fail "yarn server" "yarn client"
$ cd client && yarn start
$ nodemon server.js
$ react-scripts start
[0] [nodemon] 1.19.4
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching dir(s): *.*
[0] [nodemon] watching extensions: js,mjs,json
[0] [nodemon] starting `node server.js`
[0] Listening on port 5000
[1] Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade caniuse-lite browserslist`
[1] Starting the development server...
[1]
[1] Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`
[1] Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`
[1] Compiled successfully!
[1]
[1] You can now view create-react-app-express in the browser.
[1]
[1]   Local:            http://localhost:3000/
[1]   On Your Network:  http://10.0.0.65:3000/
[1]
[1] Note that the development build is not optimized.
[1] To create a production build, use yarn build.
[1]
[0] {}
[0] user query data: dataSTR NaN ; req string undefined; uname string undefined
[0] H:\PyProjects\login\loginproj\node_modules\mysql\lib\protocol\Parser.js:437
[0]       throw err; // Rethrow non-MySQL errors
[0]       ^
[0]
[0] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0]     at ServerResponse.setHeader (_http_outgoing.js:470:11)
[0]     at ServerResponse.header (H:\PyProjects\login\loginproj\node_modules\express\lib\response.js:771:10)
[0]     at ServerResponse.send (H:\PyProjects\login\loginproj\node_modules\express\lib\response.js:170:12)
[0]     at ServerResponse.json (H:\PyProjects\login\loginproj\node_modules\express\lib\response.js:267:15)
[0]     at Query.<anonymous> (H:\PyProjects\login\loginproj\server.js:44:36)
[0]     at Query.<anonymous> (H:\PyProjects\login\loginproj\node_modules\mysql\lib\Connection.js:525:10)
[0]     at Query._callback (H:\PyProjects\login\loginproj\node_modules\mysql\lib\Connection.js:491:16)
        at Query.Sequence.end (H:\PyProjects\login\loginproj\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
[0]     at Query._handleFinalResultPacket (H:\PyProjects\login\loginproj\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
[0]     at Query.EofPacket (H:\PyProjects\login\loginproj\node_modules\mysql\lib\protocol\sequences\Query.js:123:8)
[0] [nodemon] app crashed - waiting for file changes before starting...
[1] Proxy error: Could not proxy request /api/world from localhost:3000 to http://localhost:5000/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

2 个答案:

答案 0 :(得分:0)

根据您的代码中的错误编码多次发送响应,所以这是您的有效代码

app.post('/api/world', (req, res) => {
    try {
        console.log(req.body);
        uname = req.body.post;

        var DBuserCheck = "SELECT EXISTS (SELECT * FROM `loginschema`.credentials WHERE uname =" + '"' + uname + '"' + ")";
        var DBpwdCheck = "SELECT pwd FROM `loginschema`.credentials WHERE uname =" + '"' + uname + '"';

        connection.query(DBuserCheck, function (err, data) {
            if(err) {
                res.send(err) : res.json({ USERdata: data })
                console.log('user query data: dataSTR', +data + " ; req string " + req.body.post + "; uname string " + uname);
            } else {
                connection.query(DBpwdCheck, function (err, pdata) {
                    if (pdata == req.body.password) {
                        res.json({ Successfully_loggedin });

                    } else {
                        (err) ? res.send(err) : res.json({ pwdData_Wrong_Password: pdata });
                        console.log('enter valid credentials');
                    }
                });
            }
        });
    }
    catch (ex) {
        console.log('Message from Catch is ----->>>> ' + ex);
    }

});

答案 1 :(得分:0)

这解决了我的问题。我添加了这样的 if 语句。

if(loginUserId ===stat.userId && singlePost.id){
  return Object.assign({}, {
    stat_id: stat.id,
    is_status : true,
  })
} else if(loginUserId ===userId){
  return Object.assign({}, {
    stat_id: stat.id,
    is_status : true,
  })
}  else {
  return Object.assign({}, {
    stat_id: stat.id,
    is_status : false,
  })
}