Get your own Node server
const http = require('http');
const url = require('url');

// Create an HTTP server with routing
const server = http.createServer((req, res) => {
  // Parse the URL
  const parsedUrl = url.parse(req.url, true);
  const path = parsedUrl.pathname;
  const trimmedPath = path.replace(/^\/+|\/+$/g, '');
  
  // Get the HTTP method
  const method = req.method.toLowerCase();
  
  // Get query parameters
  const queryParams = parsedUrl.query;
  
  // Log the request
  console.log(`Request received: ${method} ${trimmedPath}`);
  
  // Route handler
  let response = {
    status: 404,
    contentType: 'application/json',
    payload: { message: 'Not Found' }
  };
  
  // Basic routing
  if (method === 'get') {
    if (trimmedPath === '') {
      // Home route
      response = {
        status: 200,
        contentType: 'text/html',
        payload: '

Home Page

Welcome to the server

' }; } else if (trimmedPath === 'api/users') { // API route - list users response = { status: 200, contentType: 'application/json', payload: { users: [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' } ] } }; } else if (trimmedPath.startsWith('api/users/')) { // API route - get user by ID const userId = trimmedPath.split('/')[2]; response = { status: 200, contentType: 'application/json', payload: { id: userId, name: `User ${userId}` } }; } } // Return the response res.setHeader('Content-Type', response.contentType); res.writeHead(response.status); // Convert payload to string if it's an object const payloadString = typeof response.payload === 'object' ? JSON.stringify(response.payload) : response.payload; res.end(payloadString); }); // Start the server const PORT = 8080; server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
Server running at http://localhost:8080/
Request received: get
Request received: get favicon.ico