Q1. How do you create a basic Express server?
First, require express:
Then create an app instance:
Define a route:
Finally, start the server:
const express = require('express');Then create an app instance:
const app = express();Define a route:
app.get('/', (req, res) => res.send('Hello World'));Finally, start the server:
app.listen(3000, () => console.log('Server running'));Q2. What is the purpose of app.listen()?
It takes a port number and an optional callback that runs when the server starts.
For example,
It returns an HTTP server object.
app.listen() binds and listens for connections on the specified port.It takes a port number and an optional callback that runs when the server starts.
For example,
app.listen(3000) makes your app accessible at http://localhost:3000.It returns an HTTP server object.
Q3. How do you send a response to the client?
You use the response object (
Common methods:
Example:
res).Common methods:
res.send() for sending HTML or text, res.json() for JSON, res.status() to set HTTP status, and res.redirect() for redirects.Example:
res.status(200).json({ message: 'Success' });Q4. What is the difference between res.send() and res.json()?
When passed an object, it automatically sets Content-Type to
Both are similar, but
res.send() can send various types (strings, objects, buffers).When passed an object, it automatically sets Content-Type to
application/json.res.json() is more explicit for JSON responses and ensures proper formatting.Both are similar, but
res.json() is preferred for APIs.Q5. How do you handle different HTTP methods in your first server?
Use
For example:
You can also use
app.get(), app.post(), app.put(), app.delete() for respective methods.For example:
app.post('/api', (req, res) => { // handle POST });You can also use
app.all() to handle all methods on a route, or app.use() for middleware.