简体   繁体   English

是否将req.query ['name']的值保存到Node.jS中的变量?

[英]Saving the value of req.query['name'] to a variable in Node.jS?

I am coding a login system in node.js, I am trying to do this: 我正在使用node.js编写登录系统,我正在尝试这样做:

var auth = req.query['name']

to which I would then compare auth with the result from the database query, but when ever I try and load the page with /?name=foo I get this error: 然后我将auth与数据库查询的结果进行比较,但是每当我尝试使用/?name = foo加载页面时,都会出现此错误:

Error: Can't set headers after they are sent.

my current code is: 我当前的代码是:

var express = require('express');
var app = express();

app.get('/', function(req, res){
    res.send('hello! every thing is working!');
    var auth = req.query['name']
    if (auth === "ozzie"){// I will obviously change this.
        res.send('Hello! Your details have been authenticated')
    }
    else
    {
        res.send('Sorry! That did not work! please try again! ')
    }
});


app.listen(8888, '127.0.0.1'); 
console.log('running on, local Ip + 8888');

The problem is that you're attempting to send two responses to the same request, the first time with 问题是您尝试发送两个对同一请求的响应,这是第一次

res.send('hello! every thing is working!');

and the second time is inside the if or else block. 第二次是在if or else块中。 Remove the first one and it should work fine or concatenate the output and have just one res.send() that is passed the concatenated output. 删除第一个,它应该可以正常工作或连接输出,只有一个res.send()传递给连接的输出。

You are sending a response at the beginning of your callback: 您正在回调的开头发送响应:

app.get('/', function(req, res){
     res.send('hello! every thing is working!'); // here

Then, calling the same thing in a conditional if - else block once more. 然后,在有条件的if - else再次调用同一事物。 Since calling the send() method sets headers, you end up doing the same twice. 由于调用send()方法设置了标头,因此您最终做了两次相同的操作。

Remove the first one and you'll be OK. 删除第一个,就可以了。

Note: For debugging purposes you could resort to using console.log and view the debug info on the console where you ran your application's main file. 注意:出于调试目的,您可以求助于console.log并在运行应用程序主文件的控制台上查看调试信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM