1

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 ?
 }
Eldar Tailov
  • 358
  • 5
  • 18
  • Does this answer your question? [Responding with a JSON object in Node.js (converting object/array to JSON string)](https://stackoverflow.com/questions/5892569/responding-with-a-json-object-in-node-js-converting-object-array-to-json-string) – luk2302 Dec 11 '22 at 06:12
  • Just set the `Content-Type` header to `application/json`, then send the stringified json `JSON.stringify(data)` – skara9 Dec 11 '22 at 06:14

1 Answers1

2

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));
}
Amir MB
  • 3,233
  • 2
  • 10
  • 16