Skip to content

Instantly share code, notes, and snippets.

@chamilaadhi
Created December 24, 2024 11:43
Show Gist options
  • Select an option

  • Save chamilaadhi/fc2a7a0223dd0db11b90d248d95c5ac3 to your computer and use it in GitHub Desktop.

Select an option

Save chamilaadhi/fc2a7a0223dd0db11b90d248d95c5ac3 to your computer and use it in GitHub Desktop.
json-backend.js
const http = require('http');
const port = 3010;
// Create an HTTP server
const server = http.createServer((req, res) => {
if (req.url === '/bookings' && req.method === 'GET') {
// Define the response JSON with multiple elements
const response = {
bookings: {
total: 42,
confirmed: 35,
pending: 7
}
};
// Set the response headers
res.writeHead(200, { 'Content-Type': 'application/json' });
// Send the JSON response
res.end(JSON.stringify(response));
} else {
// Handle 404 for other routes
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
// Start the server
server.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment