Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
NodeJS HTTP Server
const getQueryParams = function (req) {
let query = req.url.split('?');
let queryParams = {};
if (query.length >= 2) {
let params = query[1].split('&');
params.forEach((keyValuePair) => {
try {
let key = keyValuePair.split('=')[0];
let value = keyValuePair.split('=')[1];
queryParams[key] = value;
} catch (err) {
queryParams[key] = '';
}
});
}
return queryParams;
}
const requestHandler = (req, res) => {
if (req.url === '/favicon.ico') {
res.writeHead(200, {
'Content-Type': 'image/x-icon'
});
return res.end();
}
const reqQueryParams = getQueryParams(req);
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end(`Greetings from NodeJS server to ${reqQueryParams.name} ${reqQueryParams.surname}`);
}
const http = require('http'),
port = process.env.PORT || 8080;
const getQueryParams = function (req) {
let query = req.url.split('?');
let queryParams = {};
if (query.length >= 2) {
let params = query[1].split('&');
params.forEach((keyValuePair) => {
try {
let key = keyValuePair.split('=')[0];
let value = keyValuePair.split('=')[1];
queryParams[key] = value;
} catch (err) {
queryParams[key] = '';
}
});
}
return queryParams;
}
const requestHandler = (req, res) => {
if (req.url === '/favicon.ico') {
res.writeHead(200, {
'Content-Type': 'image/x-icon'
});
return res.end();
}
const reqQueryParams = getQueryParams(req);
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end(`Greetings from NodeJS server to ${reqQueryParams.name} ${reqQueryParams.surname}`);
}
http.createServer(requestHandler).listen(port, (err) => {
if (!err) {
console.log(`server is listening on ${port}`)
} else {
console.log('error during server start ', err);
}
});
const http = require('http'),
port = process.env.PORT || 8080;
const requestHandler = (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Greetings from NodeJS server');
}
http.createServer(requestHandler).listen(port, (err) => {
if (!err) {
console.log(`server is listening on ${port}`)
} else {
console.log('error during server start ', err);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment