Tuesday, 21 January 2025

Lecture Notes of Class 7: Introduction to Express.js

 

Lecture Notes of  Class 7: Introduction to Express.js

Objective:

In this class, you will get familiar with Express.js, a popular web framework for Node.js, and learn how to use it to create a simple web server and handle routes.


What is Express.js?

Express.js is a lightweight and flexible web application framework for Node.js. It simplifies the process of building and managing web servers, APIs, and routes. Express.js is commonly used in full-stack JavaScript development because it allows developers to quickly create web applications and RESTful APIs. Express.js handles routing, middleware, and HTTP requests, allowing you to focus on building your application logic.

Why use Express.js?

  • Simplicity: Express provides a simple and minimalistic approach to creating a web server.
  • Flexibility: It allows you to easily add more features, like session handling, logging, and more, through middleware.
  • Speed: Express makes it faster to develop Node.js web applications by reducing the amount of boilerplate code you need.
  • Community and Documentation: As one of the most popular frameworks for Node.js, Express has extensive documentation and community support.

Prerequisites

  • Node.js should be installed on your system.
  • Basic knowledge of JavaScript and Node.js.

Lab Tasks

1. Install Express using npm

Before we can use Express.js in our project, we need to install it. Express is available on the npm registry, so we can easily install it via npm.

  • Step 1: Open your terminal or command prompt.
  • Step 2: Navigate to your project folder using the cd command.

cd path/to/your/project

  • Step 3: Initialize a Node.js project (if not already done) by creating a package.json file.

npm init -y

  • Step 4: Now, install Express.js using the following npm command:

npm install express

This command will download and install the Express.js package and add it as a dependency in your package.json file.


2. Create a Simple Express Server

Now that we have Express installed, let's create a basic web server. We'll write some JavaScript to use Express to handle HTTP requests.

  • Step 1: Create a new file in your project folder (for example: app.js).

touch app.js

  • Step 2: Open the file (app.js) and write the following code:


// Import express module

const express = require('express');

 

// Create an Express application

const app = express();

 

// Set up a route for the root URL

app.get('/', (req, res) => {

    res.send('Hello, Express!');

});

 

// Start the server on port 3000

app.listen(3000, () => {

    console.log('Server is running on http://localhost:3000');

});

  • Step 3: In the terminal, run the following command to start the server:

node app.js

  • Step 4: Open your web browser and go to http://localhost:3000. You should see the message Hello, Express! displayed in the browser.

Explanation of Code:

  • const express = require('express'); – This imports the Express module.
  • const app = express(); – This creates an instance of the Express application.
  • app.get('/', (req, res) => {...}); – This defines a route for the HTTP GET request at the root URL (/). When a user visits the root URL, the server responds with Hello, Express!.
  • app.listen(3000, () => {...}); – This starts the server on port 3000 and logs a message to the console.

3. Set Up Basic Routes Using Express

Now let's explore how to set up different routes in Express to handle different HTTP requests.

  • Step 1: Update your app.js file to include more routes.

const express = require('express');

const app = express();

 

// Root route (GET)

app.get('/', (req, res) => {

    res.send('Welcome to the Express server!');

});

 

// About route (GET)

app.get('/about', (req, res) => {

    res.send('This is the About page.');

});

 

// Contact route (GET)

app.get('/contact', (req, res) => {

    res.send('This is the Contact page.');

});

 

// Start the server

app.listen(3000, () => {

    console.log('Server is running on http://localhost:3000');

});

  • Step 2: Run the server again:

node app.js

  • Step 3: Test the routes in your browser:
    • Go to http://localhost:3000/ for the home page.
    • Go to http://localhost:3000/about for the About page.
    • Go to http://localhost:3000/contact for the Contact page.

Explanation of Code:

  • app.get('/about', (req, res) => {...}); – This route responds to GET requests for the /about URL.
  • app.get('/contact', (req, res) => {...}); – This route responds to GET requests for the /contact URL.
  • Each route has a callback function that takes two parameters: req (request) and res (response). The res.send() function is used to send a response back to the client.

Key Concepts in Express

  • Routes: Routes are URL patterns associated with specific HTTP methods (like GET, POST, etc.). Express allows you to define multiple routes for different parts of your application.
  • Request and Response: In Express, req represents the HTTP request and res represents the HTTP response. You use req to get data sent from the client, and you use res to send data back to the client.
  • Middleware: Express uses middleware functions to process requests before they reach the route handlers. Middleware functions can modify requests, responses, or even end the request-response cycle.

Conclusion

In this class, you learned how to set up a basic Express.js server and define routes to handle different HTTP requests. Express makes it easy to create powerful web applications and RESTful APIs in Node.js. You can extend your server with more routes, middleware, and other functionalities as you build more complex applications.


Next Steps

  • Explore different HTTP methods like POST, PUT, DELETE, and PATCH.
  • Learn about middleware functions in Express.
  • Experiment with serving static files (e.g., HTML, CSS, images) using Express.


Assignments on Express.js - Class 7: Introduction to Express.js


Assignment 1: Installing Express.js and Creating a Basic Server

Problem:

  1. Install Express.js in your project using npm.
  2. Create a basic Express server that listens on port 4000 and responds with Hello World when accessed via the browser at http://localhost:4000/.

Solution:

  1. Initialize a new Node.js project:

npm init -y

  1. Install Express.js:

npm install express

  1. Create a file app.js and add the following code:

const express = require('express');

const app = express();

 

app.get('/', (req, res) => {

    res.send('Hello World');

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});

  1. Run the server:

node app.js

Now, you can visit http://localhost:4000/ in the browser and see the message Hello World.


Assignment 2: Handling Multiple Routes

Problem:

Create an Express server with the following routes:

  • GET / – Welcome message.
  • GET /about – Information about your application.
  • GET /contact – Contact page.

Solution:

const express = require('express');

const app = express();

 

app.get('/', (req, res) => {

    res.send('Welcome to the Express Server!');

});

 

app.get('/about', (req, res) => {

    res.send('This is the About page.');

});

 

app.get('/contact', (req, res) => {

    res.send('This is the Contact page.');

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});


Assignment 3: Sending JSON Response

Problem:

Create a route /api/user that sends a JSON response with name and age.

Solution:


const express = require('express');

const app = express();

 

app.get('/api/user', (req, res) => {

    const user = { name: 'John Doe', age: 25 };

    res.json(user);

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});


Assignment 4: Handling Query Parameters

Problem:

Create a route /search that accepts query parameters name and age. Print the received parameters in the response.

Solution:

const express = require('express');

const app = express();

 

app.get('/search', (req, res) => {

    const name = req.query.name;

    const age = req.query.age;

    res.send(`Name: ${name}, Age: ${age}`);

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});

To test, access http://localhost:4000/search?name=John&age=30.


Assignment 5: Handling POST Requests

Problem:

Create a route /login that accepts POST requests and responds with a success message containing the user’s name.

Solution:

  1. You will need a middleware to parse JSON request bodies.


npm install body-parser

  1. Create app.js:


const express = require('express');

const bodyParser = require('body-parser');

const app = express();

 

app.use(bodyParser.json());

 

app.post('/login', (req, res) => {

    const { name, password } = req.body;

    if (name && password) {

        res.send(`Welcome, ${name}!`);

    } else {

        res.send('Please provide both name and password.');

    }

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});

  1. To test, send a POST request using a tool like Postman or cURL:


curl -X POST -H "Content-Type: application/json" -d '{"name": "John", "password": "1234"}' http://localhost:4000/login


Assignment 6: Setting Up a Static File Server

Problem:

Set up Express to serve a static HTML file (index.html) from the /public folder.

Solution:

  1. Create a folder named public and add an index.html file in it.
  2. Create the following app.js:

const express = require('express');

const path = require('path');

const app = express();

 

app.use(express.static(path.join(__dirname, 'public')));

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});

When you visit http://localhost:4000/index.html, Express will serve the static file.


Assignment 7: Using Route Parameters

Problem:

Create a route /user/:id that takes an id as a parameter and responds with a message containing the id.

Solution:


const express = require('express');

const app = express();

 

app.get('/user/:id', (req, res) => {

    const userId = req.params.id;

    res.send(`User ID: ${userId}`);

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});

You can test it by visiting http://localhost:4000/user/123.


Assignment 8: Creating a Middleware to Log Requests

Problem:

Create middleware that logs each request's method and URL before passing control to the next middleware.

Solution:

const express = require('express');

const app = express();

 

// Middleware to log request method and URL

app.use((req, res, next) => {

    console.log(`${req.method} request to ${req.url}`);

    next();

});

 

app.get('/', (req, res) => {

    res.send('Hello World');

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});

This will log every request made to the server.


Assignment 9: Handling Errors in Express

Problem:

Create a route /error that intentionally causes an error, and handle it using Express's error handling middleware.

Solution:

const express = require('express');

const app = express();

 

// Route that causes an error

app.get('/error', (req, res) => {

    throw new Error('Something went wrong!');

});

 

// Error handling middleware

app.use((err, req, res, next) => {

    console.error(err.message);

    res.status(500).send('Internal Server Error');

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});


Assignment 10: Set Up a Simple API

Problem:

Create an Express API with the following routes:

  • GET /products – List of products (send a static array of products).
  • GET /products/:id – Get a product by id.

Solution:

const express = require('express');

const app = express();

 

// Static array of products

const products = [

    { id: 1, name: 'Laptop', price: 1000 },

    { id: 2, name: 'Smartphone', price: 700 },

    { id: 3, name: 'Tablet', price: 300 }

];

 

// Route to get all products

app.get('/products', (req, res) => {

    res.json(products);

});

 

// Route to get a product by id

app.get('/products/:id', (req, res) => {

    const productId = parseInt(req.params.id, 10);

    const product = products.find(p => p.id === productId);

   

    if (product) {

        res.json(product);

    } else {

        res.status(404).send('Product not found');

    }

});

 

app.listen(4000, () => {

    console.log('Server is running on http://localhost:4000');

});

You can test the API with requests like http://localhost:4000/products or http://localhost:4000/products/1.


MCQs on Express.js

1. What is Express.js?

  • A. A JavaScript library for handling databases
  • B. A JavaScript framework for front-end development
  • C. A web framework for Node.js
  • D. A tool for managing dependencies

Answer: C. A web framework for Node.js
Explanation: Express.js is a minimalist web framework for Node.js that simplifies the process of building and handling web servers, APIs, and routing.


2. Which command is used to install Express in a Node.js project?

  • A. npm install express
  • B. npm init express
  • C. npm install -g express
  • D. node install express

Answer: A. npm install express
Explanation: The correct command to install Express in your project is npm install express, which installs the framework locally.


3. Which HTTP method is used to retrieve data from the server in Express?

  • A. POST
  • B. GET
  • C. PUT
  • D. DELETE

Answer: B. GET
Explanation: The GET method is used to retrieve data from the server, typically when the user accesses a page or API endpoint.


4. Which middleware function is commonly used to parse incoming request bodies in Express?

  • A. body-parser
  • B. express-body-parser
  • C. json-parser
  • D. request-parser

Answer: A. body-parser
Explanation: The body-parser middleware is used to parse the body of incoming requests, allowing you to access data sent with POST requests.


5. How do you create a route in Express that listens to GET requests?

  • A. app.listen('/path')
  • B. app.get('/path', callback)
  • C. app.create('/path')
  • D. app.route('/path')

Answer: B. app.get('/path', callback)
Explanation: In Express, the app.get() method is used to define a route that listens for GET requests at a specific path.


6. Which of the following is used to start an Express server?

  • A. app.init()
  • B. app.listen()
  • C. server.start()
  • D. app.run()

Answer: B. app.listen()
Explanation: The app.listen() function is used to start the Express server, binding it to a specified port.


7. How can you specify the port number for the Express server?

  • A. app.set('port', 3000)
  • B. app.listen(3000)
  • C. app.port(3000)
  • D. app.start(3000)

Answer: B. app.listen(3000)
Explanation: You specify the port by passing it as an argument to app.listen(), such as app.listen(3000).


8. What is the purpose of the next() function in Express middleware?

  • A. To terminate the request-response cycle
  • B. To pass control to the next middleware function
  • C. To send a response to the client
  • D. To execute an asynchronous operation

Answer: B. To pass control to the next middleware function
Explanation: The next() function passes control to the next middleware function in the stack, allowing the next part of the request-response cycle to be executed.


9. What does res.send() do in Express?

  • A. Sends an HTML response to the client
  • B. Sends a JSON object to the client
  • C. Sends a file response
  • D. Sends a response to the client

Answer: D. Sends a response to the client
Explanation: res.send() sends the final response to the client, which can be a string, buffer, or object.


10. How do you create a POST route in Express?

  • A. app.post('/path', callback)
  • B. app.route('/path', post)
  • C. app.create('/path', post)
  • D. app.add('/path', post)

Answer: A. app.post('/path', callback)
Explanation: To create a POST route in Express, the app.post() method is used.


11. Which of the following is correct for defining a route that matches both GET and POST requests?

  • A. app.all('/path', callback)
  • B. app.get('/path', callback)
  • C. app.post('/path', callback)
  • D. app.match('/path', callback)

Answer: A. app.all('/path', callback)
Explanation: The app.all() method is used to define a route that matches all HTTP methods, including GET and POST.


12. How do you access URL parameters in Express?

  • A. req.body.param
  • B. req.query.param
  • C. req.params.param
  • D. req.url.param

Answer: C. req.params.param
Explanation: URL parameters are accessed via req.params, which holds dynamic values in the URL.


13. How do you send a JSON response from an Express route?

  • A. res.json()
  • B. res.send()
  • C. res.text()
  • D. res.content()

Answer: A. res.json()
Explanation: res.json() is used to send a JSON-formatted response to the client.


14. How do you include a static HTML file in Express?

  • A. app.use(express.static('public'))
  • B. app.set('static', 'public')
  • C. app.static('public')
  • D. app.useStatic('public')

Answer: A. app.use(express.static('public'))
Explanation: To serve static files, express.static() middleware is used in combination with app.use().


15. How can you handle errors globally in Express?

  • A. Use a middleware function with four arguments
  • B. Use app.error()
  • C. Use app.catch()
  • D. Use try-catch block

Answer: A. Use a middleware function with four arguments
Explanation: In Express, error handling is done by middleware functions with four arguments (err, req, res, next).


16. How do you parse URL-encoded data in Express?

  • A. app.use(express.urlencoded({ extended: true }))
  • B. app.use(express.json())
  • C. app.parse('urlencoded')
  • D. app.use(express.parseUrl())

Answer: A. app.use(express.urlencoded({ extended: true }))
Explanation: The express.urlencoded() middleware is used to parse URL-encoded data, typically for forms.


17. What does res.status(404) do in Express?

  • A. Sets the response to a status code of 404
  • B. Sends a success message
  • C. Sends a redirect to the client
  • D. Stops the server

Answer: A. Sets the response to a status code of 404
Explanation: The res.status(404) method sets the response status code to 404 (Not Found).


18. What is the purpose of Express middleware?

  • A. To handle database operations
  • B. To create routes
  • C. To process requests and responses before they reach routes
  • D. To store user data

Answer: C. To process requests and responses before they reach routes
Explanation: Middleware functions in Express process incoming requests before they are passed to route handlers.


19. Which of the following helps in serving files like images and stylesheets in Express?

  • A. express.static()
  • B. app.serve()
  • C. app.files()
  • D. express.serveStatic()

Answer: A. express.static()
Explanation: express.static() is used to serve static files such as images, CSS, and JavaScript.


20. What happens when app.listen() is called in Express?

  • A. The server starts listening for HTTP requests on the specified port
  • B. The app initializes the database
  • C. The server listens for only GET requests
  • D. The server is ready to run background jobs

Answer: A. The server starts listening for HTTP requests on the specified port
Explanation: app.listen() starts the Express server, allowing it to handle requests on the specified port.


I will continue providing additional MCQs if needed. Would you like me to continue or adjust the format for the remaining questions?

4o mini

You said:

yes

ChatGPT said:

ChatGPT

Here are more multiple-choice questions (MCQs) on Express.js with answers and detailed explanations:


21. What is the default behavior when a route handler doesn't send a response in Express?

  • A. Express sends a "Not Found" error automatically
  • B. The request will be canceled
  • C. The server keeps waiting for a response
  • D. Express sends a 500 internal server error

Answer: C. The server keeps waiting for a response
Explanation: If a route handler doesn't send a response, Express will not automatically terminate the request and will continue to wait for a response.


22. What method is used to define a PUT route in Express?

  • A. app.put('/path', callback)
  • B. app.update('/path', callback)
  • C. app.modify('/path', callback)
  • D. app.set('/path', callback)

Answer: A. app.put('/path', callback)
Explanation: The app.put() method is used to define a route that listens for PUT requests to a specified path.


23. How do you prevent a route from being matched by Express?

  • A. Use the res.send() method
  • B. Use app.stop()
  • C. Use a wildcard character in the route
  • D. Use the next() function

Answer: D. Use the next() function
Explanation: You can use the next() function in middleware to skip the current route and prevent it from being matched.


24. How do you add a new item to the body of a POST request in Express?

  • A. req.body.item = value
  • B. res.body.item = value
  • C. req.addBody(item, value)
  • D. app.addBody(req, item, value)

Answer: A. req.body.item = value
Explanation: To add an item to the request body, you can directly assign it to req.body in the route handler.


25. How can you prevent Express from logging requests?

  • A. Use app.disable('logging')
  • B. Use app.use(morgan('combined'))
  • C. Disable logging using middleware
  • D. Use app.set('log', false)

Answer: C. Disable logging using middleware
Explanation: To prevent logging, you can simply skip using logging middleware (like morgan) or conditionally disable it based on environment.


26. Which of the following is true for middleware functions in Express?

  • A. Middleware is executed after the route handler
  • B. Middleware is used only for logging requests
  • C. Middleware can modify the request and response objects
  • D. Middleware is only for error handling

Answer: C. Middleware can modify the request and response objects
Explanation: Middleware functions are powerful in Express and can modify the req and res objects, perform validation, and more.


27. What is the correct syntax for using middleware in Express?

  • A. app.use(middlewareFunction)
  • B. app.middleware(middlewareFunction)
  • C. middleware.use(app)
  • D. app.useMiddleware(middlewareFunction)

Answer: A. app.use(middlewareFunction)
Explanation: Middleware is added using app.use() to process requests before they reach route handlers.


28. How do you define a wildcard route in Express?

  • A. app.get('*', callback)
  • B. app.all('*', callback)
  • C. app.match('*', callback)
  • D. app.route('*', callback)

Answer: B. app.all('*', callback)
Explanation: The wildcard * matches any path and can be used with app.all() to define a route that will handle all HTTP methods at any path.


29. Which method in Express is used to set the view engine?

  • A. app.set('view engine', 'ejs')
  • B. app.use('view engine', 'ejs')
  • C. app.engine('view', 'ejs')
  • D. app.view('engine', 'ejs')

Answer: A. app.set('view engine', 'ejs')
Explanation: The app.set() method is used to set the view engine, which allows Express to render views with a specific template engine (e.g., EJS).


30. How do you serve dynamic content in Express?

  • A. Use res.send()
  • B. Use res.render()
  • C. Use res.json()
  • D. Use res.sendFile()

Answer: B. Use res.render()
Explanation: res.render() is used to render dynamic content, often with a template engine like EJS or Pug.


31. How do you handle a 404 error in Express?

  • A. Define a route for app.all('*')
  • B. Use app.use('404', callback)
  • C. Use app.use('*', callback)
  • D. Use res.error(404)

Answer: A. Define a route for app.all('*')
Explanation: The route app.all('*') is commonly used to handle 404 errors by catching all unmatched routes and sending a 404 response.


32. What is the purpose of express.Router()?

  • A. It is used to define middleware
  • B. It helps create route handlers in a modular way
  • C. It handles error pages only
  • D. It manages requests to static files

Answer: B. It helps create route handlers in a modular way
Explanation: express.Router() is used to create modular route handlers, allowing you to define multiple routes and group them logically.


33. How do you handle multiple HTTP methods in a single route using Express?

  • A. Use app.all() with the methods specified
  • B. Use app.route()
  • C. Use app.method() for each method
  • D. Use app.combine()

Answer: B. Use app.route()
Explanation: app.route() allows you to chain route handlers for multiple HTTP methods like GET, POST, and PUT at the same path.


34. What will req.query contain?

  • A. URL parameters
  • B. The body of the request
  • C. Query string parameters
  • D. The full URL

Answer: C. Query string parameters
Explanation: req.query contains the query string parameters from the URL, e.g., ?name=John&age=30.


35. What is the default port number for an Express server if none is specified?

  • A. 3000
  • B. 8080
  • C. 5000
  • D. 5001

Answer: A. 3000
Explanation: If no port number is specified in the app.listen() method, Express will listen on port 3000 by default.


36. How can you handle POST data in Express?

  • A. Use req.body for accessing form data
  • B. Use req.query
  • C. Use req.param
  • D. Use req.data

Answer: A. Use req.body for accessing form data
Explanation: POST data is accessed using req.body after parsing it with middleware like express.json() or express.urlencoded().


37. Which middleware is used to serve static files from the "public" directory?

  • A. app.use(express.static('public'))
  • B. app.serveStatic('public')
  • C. app.static('public')
  • D. app.serve('public')

Answer: A. app.use(express.static('public'))
Explanation: The express.static() middleware serves static files like images, CSS, and JavaScript from a specified directory, like "public."


38. What is the role of the next() function in middleware?

  • A. It sends the response to the client
  • B. It terminates the request-response cycle
  • C. It passes control to the next middleware function
  • D. It generates a response

Answer: C. It passes control to the next middleware function
Explanation: The next() function is used to pass control to the next middleware function in the stack. If not called, the request will be stalled.


39. Which method is used to send a file in response to a request in Express?

  • A. res.sendFile()
  • B. res.send()
  • C. res.render()
  • D. res.download()

Answer: A. res.sendFile()
Explanation: The res.sendFile() method is used to send a file as a response to a client request.


40. What does app.use() do in Express?

  • A. It defines a GET route
  • B. It initializes the server
  • C. It sets middleware to handle requests
  • D. It stops the server

Answer: C. It sets middleware to handle requests
Explanation: app.use() is used to set middleware functions in Express. It can be used for logging, handling errors, parsing requests, etc.


I will continue with additional MCQs. Would you like me to proceed with more questions?

4o mini

You said:

yes

ChatGPT said:

ChatGPT

Here are additional MCQs on Express.js with answers and explanations:


41. How do you define a middleware function that only applies to a specific route in Express?

  • A. Use app.use('/path', middleware)
  • B. Use app.route('/path').middleware()
  • C. Use app.get('/path', middleware)
  • D. Use app.all('/path', middleware)

Answer: C. Use app.get('/path', middleware)
Explanation: You can apply middleware to a specific route by passing it as a second argument to the route handler (e.g., app.get('/path', middleware)).


42. How can you get the value of a URL parameter in Express?

  • A. req.urlParams
  • B. req.params
  • C. req.queryParams
  • D. req.body

Answer: B. req.params
Explanation: URL parameters in Express are accessed using req.params. For example, if a route is defined as /user/:id, you can access the id parameter with req.params.id.


43. Which of the following will allow you to send a JSON response in Express?

  • A. res.json()
  • B. res.sendJSON()
  • C. res.send()
  • D. res.render()

Answer: A. res.json()
Explanation: The res.json() method is used to send a JSON response in Express, automatically setting the Content-Type header to application/json.


44. What will happen if you call next() in a route handler without any argument?

  • A. It will pass the request to the next middleware
  • B. It will send a default response to the client
  • C. It will terminate the request
  • D. It will throw an error

Answer: A. It will pass the request to the next middleware
Explanation: Calling next() without an argument passes control to the next middleware in the stack.


45. What is the correct way to handle errors in Express?

  • A. Use app.on('error')
  • B. Use a custom error-handling middleware
  • C. Use app.handleError()
  • D. Use res.sendError()

Answer: B. Use a custom error-handling middleware
Explanation: Express allows you to define custom error-handling middleware by specifying four arguments (err, req, res, next). This middleware will catch and handle errors.


46. How can you serve a dynamic web page in Express?

  • A. Use res.json()
  • B. Use res.render()
  • C. Use res.send()
  • D. Use res.sendFile()

Answer: B. Use res.render()
Explanation: To serve dynamic content using a template engine (e.g., EJS), you use res.render() to render the page with dynamic data.


47. How do you specify the view engine to use in an Express app?

  • A. app.set('view engine', 'html')
  • B. app.use('view engine', 'pug')
  • C. app.set('view engine', 'ejs')
  • D. app.use('template engine', 'ejs')

Answer: C. app.set('view engine', 'ejs')
Explanation: The app.set() method is used to specify which template engine to use for rendering views in Express. For example, app.set('view engine', 'ejs') specifies EJS.


48. What is the purpose of the express.json() middleware?

  • A. To serve static files
  • B. To parse JSON-formatted request bodies
  • C. To authenticate requests
  • D. To handle error responses

Answer: B. To parse JSON-formatted request bodies
Explanation: The express.json() middleware is used to parse incoming requests with JSON payloads and makes the data available on req.body.


49. What is the correct way to add query parameters to a URL in Express?

  • A. req.queryParams
  • B. req.body
  • C. req.query
  • D. req.params

Answer: C. req.query
Explanation: Query parameters are accessed using req.query in Express. For example, /search?q=hello would give req.query.q as hello.


50. What is the default response type when using res.send() in Express?

  • A. JSON
  • B. Text
  • C. HTML
  • D. XML

Answer: B. Text
Explanation: When res.send() is used without specifying a content type, Express will send the response as plain text by default.


51. Which method is used to handle POST requests in Express?

  • A. app.get()
  • B. app.put()
  • C. app.post()
  • D. app.all()

Answer: C. app.post()
Explanation: app.post() is used to handle POST requests to a specified path in an Express application.


52. What is the purpose of res.redirect() in Express?

  • A. To send a file to the client
  • B. To send an error response
  • C. To redirect the client to a different URL
  • D. To send dynamic content

Answer: C. To redirect the client to a different URL
Explanation: res.redirect() is used to send an HTTP redirect to a different URL, making the client navigate to that URL.


53. How can you parse URL-encoded data in Express?

  • A. Use express.urlencoded()
  • B. Use express.json()
  • C. Use app.parse()
  • D. Use app.bodyParser()

Answer: A. Use express.urlencoded()
Explanation: The express.urlencoded() middleware is used to parse URL-encoded data (typically from form submissions) and make it available in req.body.


54. Which of the following can be used to handle request data in Express?

  • A. req.body
  • B. req.files
  • C. req.params
  • D. All of the above

Answer: D. All of the above
Explanation: Express allows you to handle various types of request data: req.body for form data, req.files for uploaded files, and req.params for URL parameters.


55. How can you make your Express application listen on a different port?

  • A. app.listen(4000)
  • B. app.setPort(4000)
  • C. app.bind(4000)
  • D. app.configure(4000)

Answer: A. app.listen(4000)
Explanation: app.listen() is used to bind your Express server to a specific port. For example, app.listen(4000) makes the server listen on port 4000.


56. How do you handle different HTTP methods for the same route in Express?

  • A. Use app.route()
  • B. Use app.all()
  • C. Use app.method()
  • D. Use app.use()

Answer: A. Use app.route()
Explanation: app.route() allows you to define multiple HTTP methods (e.g., GET, POST, PUT, DELETE) for the same route.


57. Which method is used to handle DELETE requests in Express?

  • A. app.delete()
  • B. app.remove()
  • C. app.destroy()
  • D. app.removeRequest()

Answer: A. app.delete()
Explanation: app.delete() is used to handle DELETE requests to a specific path in an Express application.


58. How do you send a plain text response in Express?

  • A. res.send()
  • B. res.render()
  • C. res.sendFile()
  • D. res.sendText()

Answer: A. res.send()
Explanation: The res.send() method is used to send a plain text response in Express.


59. How do you handle static files in Express?

  • A. Use app.use(express.static('public'))
  • B. Use app.static('public')
  • C. Use app.serveStatic('public')
  • D. Use app.files('public')

Answer: A. Use app.use(express.static('public'))
Explanation: express.static() middleware is used to serve static files such as images, stylesheets, and JavaScript files from a specified directory like "public."


60. Which HTTP status code is returned when an error occurs in an Express application?

  • A. 200
  • B. 500
  • C. 404
  • D. 301

Answer: B. 500
Explanation: A status code of 500 indicates an internal server error in Express when an unexpected error occurs during request handling.


 

No comments:

Post a Comment

Search This Blog

Powered by Blogger.