Reputation: 3160
I am making a simple server with nodejs for practice. When I run it, the server logs the request's URL only once (it should do so upon each request). The code enclosed in the if statement is never run, even when the request is '/update'.
Code:
var html = require('http');
score = 0;
var s = html.createServer(
function(request, response)
{
console.log('Request for \'' + request.url + '\' recieved.');
if (request.url === '/update')
{
score++;
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(score.toString());
}
else
{
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.end('\'' + request.url + '\' not found.');
}
}
);
s.listen(process.env.PORT, process.env.IP);
Output when requesting /update:
'/update' not found.
I am running the code on the Cloud 9 online IDE.
What have I done wrong?
Thanks, Sam.
Upvotes: 1
Views: 153
Reputation: 6158
Try this one it will work
var html = require('http');
score = 0;
var s = html.createServer(
function(request, response)
{
console.log('Request for \'' + request.url + '\' recieved.');
if (request.url === '/')
{
score++;
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(score.toString());
}
else
{
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.end('\'' + request.url + '\' not found.');
}
}
);
s.listen(process.env.PORT, process.env.IP);
Becuase request.url is logging as '/'
Output: 1
Upvotes: 1