9951 explained code solutions for 126 technologies


nodejsHow to send JSON response from HTTP server


const http = require('http');

const server = http.createServer((req, res) => {
  let data = {name: 'Joe', age: 98};
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify(data));
});

server.listen(82, '127.0.0.1');ctrl + c
require('http')

import module to work with http protocol

http.createServer

creates HTTP server

(req,

object with request data

res

object to manage response

application/json

set response content type to let client know we're sending JSON

JSON.stringify

convert given object to JSON string

.end(

finished http response with given content