pgonzaleznetwork pgonzaleznetwork - 5 months ago 14
Node.js Question

Node js app gets stuck while routing

I have the following server.js file

var express = require("express"),
http = require("http"),
app;

app = express();

//set up a static file directory to use for detaulf routing
app.use(express.static(__dirname+"/client"));

http.createServer(app).listen(3000);

app.get("/hello",function(req,res){
res.set("hello team!");
});


In the /client directory, I have a file called "index.html", so when I go to localhost:3000/index.html, this file is displayed, this is what I expect.

But if I then go to localhost:3000/hello the page never loads and gets stuck on "waiting for localhost" until it times out with a "no data received" error message.

If I remove the line of code for /client and just leave the routes, then it works fine. So it sounds to me like it's getting stuck trying to find "/hello" under my /client directory, but if i understand correctly, the way this works is if the file is not found on that directory, the server should try to use the other routes.

Thoughts?

Answer

There is an issue in /hello route. You used res.set("hello team!"); which is used to set HTTP header for response, not for sending the response.

Instead use res.send('hello team!'); to send response to client.

Reference: http://expressjs.com/en/api.html#res.set

Comments