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 ?
 }
2

1 Answer 1

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.