nodejs http code example
Example 1: nodejs http server
const http = require("http");
const PORT = 3000;
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.write("This is home page.");
res.end();
} else if (req.url === "/about" && req.method === "GET") {
res.write("This is about page.");
res.end();
} else {
res.write("Not Found!");
res.end();
}
});
server.listen(PORT);
console.log(`Server is running on PORT: ${PORT}`);
Example 2: node http request
const https = require('https')
const options = {
hostname: 'whatever.com',
port: 443,
path: '/todos',
method: 'GET'
}
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.end()
Example 3: node js response header
response.setHeader("Content-Type", "text/html");