Home > Enterprise >  How to send JSON data back to client in vanilla Nodejs
How to send JSON data back to client in vanilla Nodejs

Time:12-12

I need to send json data to the client in Nodejs NOT using Express or any other frameworks. How is it possible to achieve ?

const server = http.createServer(function(request, response){
    switch (request.url){
        case '/':
            mainPage(request, response);
            break;
        default:
            response.writeHead(404);
            response.end('Page not found');
    }
})

function mainPage(request, response){
    const clientData = {"status": "ok"}

    .... // send back to client, how ?
 }

CodePudding user response:

You can write on the response object:

function mainPage(request, response) {
    const data = {"status": "ok"};
    response.writeHead(200, {"Content-Type": "application/json"});
    response.end(JSON.stringify(data));
}
  • Related