简体   繁体   中英

undefined null error in node.js with redis server?

My node.js code to connect redis server is like this

    var http = require("http"),
  querystring = require("querystring"),
  redis = require("redis"),
  db = redis.createClient(6379, "127.0.0.1"); 

db.set("Jaime", "Developer", function(){});

http.createServer(function(req, res) {
  var qs = querystring.parse(req.url.split("?")[1]),
    firstName = qs.firstName;

  db.get(firstName, function(err, lastName) {
    var userName = firstName + " " + lastName,
      html = "<!doctype html>" +
        "<html><head><title>Hello " + userName + "</title></head>" +
        "<body><h1>Hello, " + userName + "!</h1></body><h2>I am in this page</h2></html>";

    res.end(html);

  });
}).listen(8000);

my redis server is also running and give a message like this

[3648] 13 Oct 11:43:00 * The server is now ready to accept connections on port 6 379 [3648] 13 Oct 11:43:01 - DB 0: 3 keys (0 volatile) in 4 slots HT. [3648] 13 Oct 11:43:01 - 0 clients connected (0 slaves), 672976 bytes in use [3648] 13 Oct 11:43:06 - DB 0: 3 keys (0 volatile) in 4 slots HT. [3648] 13 Oct 11:43:06 - 0 clients connected (0 slaves), 672976 bytes in use

when I connect it with browser (http://localhost:8000) the server status gives

[3648] 13 Oct 11:45:07 - Accepted 127.0.0.1:1715 [3648] 13 Oct 11:45:10 - DB 0: 3 keys (0 volatile) in 4 slots HT. [3648] 13 Oct 11:45:11 - 1 clients connected (0 slaves), 680892 bytes in use

and the browser out is this

Hello, undefined null! I am in this page

I am a entirely new to this .. I don't know how to make this work please help me.

You have two problems.

First, db.set is an asynchronous operation, but you have an anonymous function in the callback with nothing in it, so there is no guarantee that the operation has completed by the time you get down to the get.

You need to nest the later code inside the db.set callback (can get messy) or use a flow control library for node like async.

Second, you retrieve firstName from query params, and then don't pass anything in ... Hence the first undefined, eghttp://localhost:8000/?firstName=Jaime (this is actually what is causing the error).

You need to get both fixed for this to work. I'd read up on async operations in node, and async libraries.

(edited to add links).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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