In this tutorial we’ll take a look at how to create a HTTP server in Node.js.
If you have a need to stand up a small HTTP server to serve a simple web page or some JSON data you can use Node’s built in http
module.
To serve some HTML:
const { createServer } = require('http');
const server = createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('Hello World
');
return response.end();
});
server.listen(8080);
Or some JSON data:
const { createServer } = require('http');
const user = {
name: 'Erin',
role: 'Developer',
skills: ['JavaScript', 'Git', 'React', 'Mongo']
};
const server = createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'application/json'});
response.write(JSON.stringify(user));
return response.end();
});
server.listen(8080);
Notice how you need to specify the correct headers that the server should respond with using the writeHead
function.
The actual data that is served is supplied by the write
function and nothing will happen until you call the end
function which will finalise the request to the browser or whatever program that initiated the request.