NodeJS - Sending JSON Response with http


Install dependencies.

npm init
npm install http --save
const http = require('http');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
    const { url } = req;
    console.log(url);
    if (url === '/translation') {
        const translation = {
            1: "One",
            2: "Two",
            3: "Three"
        };
        res.setHeader('Content-Type', 'application/json');
        res.write(JSON.stringify(translation));
        res.end();
    }
    res.end('Welcome to Node.');
});

server.listen(port, hostname, () => {
    console.log(`Server Started at ${hostname}:${port}`);
});