Reputation: 2140
In the following code, I want to read the parameters from the link and display them. I used two separate if statements to check each parameter. The problem is it only reads the first if statement and discards the second one (does not check the second parameter):
var http = require('http');
var url = require('url');
var server = http.createServer(function (request, response) {
if (request.method == 'GET') {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});
// if parameter is provided
if (queryData.name) {
response.end('Hello ' + queryData.name + '\n');
} else {
response.end("Hello World\n");
}
if (queryData.age) {
response.end('Your age is ' + queryData.age + '\n');
} else {
response.end("No age provided\n");
}
}
});
// Listen on port 3000, IP defaults to 127.0.0.1 (localhost)
server.listen(8081);
The link is:
http://127.0.0.1:8081/start?name=john&age=25
Upvotes: 0
Views: 113
Reputation: 837
Do not use response.end
. Instead use response.write
and add an response.end()
after both if-statements.
See docs: https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback
Upvotes: 3