
🚀 Express.js Cheat Sheet
1️⃣ Setup & Basic Server // Import Express const express = require ( ' express ' ); const app = express (); const PORT = 3000 ; // Basic middleware app . use ( express . json ()); // Parse JSON bodies app . use ( express . urlencoded ({ extended : true })); // Parse URL-encoded bodies // Basic route app . get ( ' / ' , ( req , res ) => { res . send ( ' Hello World! ' ); }); // Start server app . listen ( PORT , () => { console . log ( `Server running on http://localhost: ${ PORT } ` ); }); // Start server with error handling const server = app . listen ( PORT , () => { console . log ( `Server running on port ${ PORT } ` ); }); server . on ( ' error ' , ( error ) => { if ( error . code === ' EADDRINUSE ' ) { console . error ( `Port ${ PORT } is already in use` ); } console . error ( ' Server error: ' , error ); }); 2️⃣ Routing Methods // GET - Retrieve data app . get ( ' /users ' , ( req , res ) => { res . json ({ message : ' Get all users ' }); }); // POST - Create new resource app . p
Continue reading on Dev.to JavaScript
Opens in a new tab




