1. Home
  2. Explore
  3. Computer Science
  4. Express.js REST API

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Express.js REST API

  • 34Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Project Setup

What is the primary purpose of npm init -y when setting up an Express.js application?

34 questions

  1. 1

    What is the primary purpose of npm init -y when setting up an Express.js application?

    1. A

      It initializes a Node.js project and generates the package.json file.

    2. B

      It creates a new directory for the Express.js application files.

    3. C

      It automatically sets up hot reloading for the Node.js application.

    4. D

      It installs the Express.js framework globally on your system.

    Correct answer
    A

    It initializes a Node.js project and generates the package.json file.

    Explanation

    The command npm init -y is used to initialize a new Node.js project. The -y flag automatically answers 'yes' to all prompts, quickly generating a package.json file, which is essential for managing project dependencies and scripts.

  2. 2

    Which command is used to install Express.js as a dependency for a Node.js project?

    1. A

      npm install express --global

    2. B

      npm init express --package

    3. C

      npm start express --save-dev

    4. D

      npm install express --save-prod

    Correct answer
    D

    npm install express --save-prod

    Explanation

    To install Express.js as a project dependency, the command npm install express is used. The --save-prod is often implied or can be explicitly added, making express a production dependency recorded in package.json.

  3. 3

    What is the conventional file name for the main server application in an Express.js project?

    1. A

      The file is commonly referred to as index.js or main.js.

    2. B

      The file should always be named app.js for clarity.

    3. C

      The file must be named server.js to function correctly.

    4. D

      The file is typically named main.js for most applications.

    Correct answer
    A

    The file is commonly referred to as index.js or main.js.

    Explanation

    While you can name the main server file whatever you prefer, the common conventions are index.js or main.js. The content explicitly mentions index.js as the chosen convention for the example.

  4. 4

    How do you instantiate an Express.js application object after requiring the Express module?

    1. A

      const app = new ExpressApplication();

    2. B

      const app = Express();

    3. C

      const app = express.createApp();

    4. D

      const app = express();

    Correct answer
    D

    const app = express();

    Explanation

    After importing the Express module using const express = require('express');, you instantiate an Express application by invoking express() as a function: const app = express();.

  5. 5

    Which method is used to start the Express.js server and make it listen for incoming requests?

    1. A

      app.start(port, callback);

    2. B

      app.listen(port, callback);

    3. C

      app.run(port, callback);

    4. D

      app.connect(port, callback);

    Correct answer
    B

    app.listen(port, callback);

    Explanation

    The app.listen() method is used to bind the server to a specific port and listen for connections. It takes the port number as the first argument and an optional callback function to execute once the server starts.

  6. 6

    What command is used to execute a Node.js application file (e.g., index.js) from the terminal?

    1. A

      execute index.js

    2. B

      node index.js

    3. C

      node run index.js

    4. D

      start index.js

    Correct answer
    B

    node index.js

    Explanation

    To run a Node.js application, you use the node command followed by the name of the main JavaScript file, for example, node index.js. This executes the script in the Node.js runtime.

  7. 7

    Why would localhost:3000 show 'Cannot GET /' after setting up an Express server initially?

    1. A

      The application has not yet defined any specific routes to handle requests.

    2. B

      The server is not configured to listen on port 3000 correctly.

    3. C

      The package.json file is missing a 'start' script for the server.

    4. D

      There is a firewall blocking incoming connections to port 3000.

    Correct answer
    A

    The application has not yet defined any specific routes to handle requests.

    Explanation

    When an Express server is running but displays 'Cannot GET /' for the root URL, it indicates that no route handler has been defined for the root path ('/') and the HTTP GET method. The server is up, but it doesn't know how to respond to that specific request.

  8. 8

    Which HTTP verb is considered best practice for retrieving data in a REST API?

    1. A

      The GET verb is the standard for requesting data from a server.

    2. B

      The PUT verb should be used when simply fetching data.

    3. C

      The POST verb is most appropriate for fetching information.

    4. D

      The PATCH verb is typically used for data retrieval operations.

    Correct answer
    A

    The GET verb is the standard for requesting data from a server.

    Explanation

    In RESTful API design, the GET HTTP verb is specifically intended for retrieving resources or data from the server. It should not have side effects and is idempotent and safe.

  9. 9

    What are the two standard parameters passed to the callback function of an Express route handler?

    1. A

      req (request) and res (response)

    2. B

      err (error) and data (response data)

    3. C

      path (route path) and handler (callback function)

    4. D

      req (request) and next (next middleware function)

    Correct answer
    A

    req (request) and res (response)

    Explanation

    The callback function for an Express route handler always receives two primary parameters: req (the request object, containing incoming request details) and res (the response object, used to send data back to the client).

  10. 10

    How can an Express route handler send back JSON data as a response to the client?

    1. A

      res.write(JSON.stringify(data));

    2. B

      res.sendJson(data);

    3. C

      res.json(data);

    4. D

      res.return(data, 'json');

    Correct answer
    C

    res.json(data);

    Explanation

    The res.json() method in Express is specifically designed to send a JSON response to the client. It automatically sets the Content-Type header to application/json and converts the JavaScript object or array to a JSON string.

  11. 11

    What is nodemon primarily used for in Node.js development?

    1. A

      It automatically restarts the Node.js application on file changes.

    2. B

      It manages Node.js package dependencies during installation.

    3. C

      It provides a debugger for stepping through Node.js code.

    4. D

      It encrypts sensitive data transmitted over the network.

    Correct answer
    A

    It automatically restarts the Node.js application on file changes.

    Explanation

    nodemon is a utility that monitors for any changes in your source code and automatically restarts your Node.js server. This is crucial for development as it provides a 'hot reload' experience, saving developers from manually restarting the server after every change.

  12. 12

    How do you install nodemon globally on your system using npm?

    1. A

      npm install nodemon --save-dev

    2. B

      npm install nodemon -g

    3. C

      npm add nodemon -g

    4. D

      npm init nodemon -y

    Correct answer
    B

    npm install nodemon -g

    Explanation

    To install nodemon globally, making it available from any directory, you use npm install nodemon -g. The -g flag indicates a global installation. For Mac/Linux, sudo might be needed before npm.

  13. 13

    Where should a dev script for running nodemon be added in a Node.js project?

    1. A

      Directly in the index.js file at the top.

    2. B

      Inside the dependencies section of package.json.

    3. C

      In a separate nodemon.json configuration file.

    4. D

      Within the scripts section of the package.json file.

    Correct answer
    D

    Within the scripts section of the package.json file.

    Explanation

    Custom scripts, such as a dev script for nodemon, are defined within the scripts section of the package.json file. This allows you to run commands like npm run dev to execute nodemon index.js.

  14. 14

    Which tool can be used to test various HTTP requests (GET, POST, PUT, DELETE) to an API?

    1. A

      The npm command-line interface

    2. B

      A standard web browser's address bar

    3. C

      Postman or Insomnia

    4. D

      Node.js built-in HTTP module

    Correct answer
    C

    Postman or Insomnia

    Explanation

    Tools like Postman and Insomnia are API clients that allow developers to construct and send various HTTP requests (GET, POST, PUT, PATCH, DELETE, etc.), inspect responses, and manage request headers and bodies, making them invaluable for API testing.

  15. 15

    What is the appropriate HTTP verb for adding new data to a resource on the server?

    1. A

      The POST verb is designated for creating or adding new data.

    2. B

      The GET verb is ideal for submitting new data records.

    3. C

      The DELETE verb can also be used for data insertion.

    4. D

      The PUT verb is primarily used for creating new resources.

    Correct answer
    A

    The POST verb is designated for creating or adding new data.

    Explanation

    The POST HTTP verb is the standard and best practice for sending data to the server to create a new resource. It is typically used for submitting forms or uploading files.

  16. 16

    Where is data typically passed when making a POST request to create a new resource in a REST API?

    1. A

      The data is passed as part of the dynamic route parameters.

    2. B

      The data is usually included within the HTTP request headers.

    3. C

      The data is always appended as query parameters in the URL path.

    4. D

      The data is commonly sent within the body of the request.

    Correct answer
    D

    The data is commonly sent within the body of the request.

    Explanation

    When creating a new resource via a POST request, the data representing the new resource is typically sent in the body of the HTTP request. This allows for sending complex data structures, often in JSON format.

  17. 17

    What is the purpose of app.use(express.json()) in an Express.js application?

    1. A

      It automatically compresses JSON responses for faster transmission.

    2. B

      It parses incoming request bodies with JSON payloads.

    3. C

      It validates the JSON structure of outgoing responses.

    4. D

      It enables the application to serve static JSON files from the server.

    Correct answer
    B

    It parses incoming request bodies with JSON payloads.

    Explanation

    app.use(express.json()) is a built-in middleware function in Express. It parses incoming requests with JSON payloads, making the parsed data available under req.body. Without this middleware, req.body would be undefined when JSON data is sent.

  18. 18

    How do you access the title property from a JSON request body in an Express route handler?

    1. A

      const title = req.query.title;

    2. B

      const title = req.headers.title;

    3. C

      const title = req.body.title;

    4. D

      const title = req.params.title;

    Correct answer
    C

    const title = req.body.title;

    Explanation

    After using express.json() middleware, data sent in the request body (like a JSON object with a title property) becomes accessible through req.body.title. Destructuring const { title } = req.body; is also a common practice.

  19. 19

    What external package is recommended for generating unique string identifiers for records?

    1. A

      The uuid package for creating unique IDs.

    2. B

      The crypto module built into Node.js.

    3. C

      The id-generator npm library for sequential numbers.

    4. D

      A simple timestamp concatenated with a random number.

    Correct answer
    A

    The uuid package for creating unique IDs.

    Explanation

    The uuid package is a popular choice for generating universally unique identifiers (UUIDs), which are often used as unique string IDs for database records or resources in a REST API, as demonstrated with v4 UUIDs.

  20. 20

    What is the typical response sent back after successfully adding a new record via a POST request?

    1. A

      A success message with status code 200.

    2. B

      An empty response with no body.

    3. C

      The newly added record itself.

    4. D

      The entire updated list of records.

    Correct answer
    C

    The newly added record itself.

    Explanation

    While there are different approaches, the content suggests that for most POST requests that add data, it is common practice to respond with the record that was newly added. This allows the client to confirm the creation and receive the full data, including any server-generated fields like an ID.

  21. 21

    How is a dynamic ID parameter (e.g., :id) accessed from the URL in an Express route handler?

    1. A

      By parsing the ID directly from req.url.

    2. B

      By extracting the ID from req.params.id.

    3. C

      By using req.body.id to retrieve the ID.

    4. D

      By accessing req.query.id for the ID.

    Correct answer
    B

    By extracting the ID from req.params.id.

    Explanation

    When a route path includes a dynamic segment like /todos/:id, the value of :id is captured and made available in the req.params object as req.params.id. This is how you access specific resource identifiers from the URL path.

  22. 22

    Why does the todos array become empty after every server restart in the given example?

    1. A

      The todos array is a global variable and gets reset by nodemon.

    2. B

      The package.json configuration forces a reset of application state.

    3. C

      The data is not persisted to a database and resides only in memory.

    4. D

      The application explicitly clears the array upon server startup.

    Correct answer
    C

    The data is not persisted to a database and resides only in memory.

    Explanation

    In the provided example, the todos array is a simple in-memory variable. When the server restarts (e.g., due to nodemon detecting changes), the Node.js process is re-initialized, and all in-memory variables, including the todos array, are reset to their initial state. Data persistence requires a database.

  23. 23

    Which HTTP verb is typically used for updating an existing resource entirely or toggling a status?

    1. A

      The PUT verb is generally used for replacing or updating resources.

    2. B

      The POST verb is suitable for modifying existing data entries.

    3. C

      The PATCH verb is the most common for full resource updates.

    4. D

      The GET verb is preferred for changing the state of a resource.

    Correct answer
    A

    The PUT verb is generally used for replacing or updating resources.

    Explanation

    The PUT HTTP verb is commonly used for updating existing resources. It typically replaces the entire resource with the new data provided. The example uses it to toggle a completed status, which is a specific type of update.

  24. 24

    How do you find the index of an element in an array based on a condition, as shown for updating a to-do?

    1. A

      Use array.indexOf(element.id === id) to get the index.

    2. B

      Iterate with forEach and store the index manually.

    3. C

      Employ array.findIndex(item => item.id === id) for the index.

    4. D

      Utilize array.find(item => item.id === id).index() directly.

    Correct answer
    C

    Employ array.findIndex(item => item.id === id) for the index.

    Explanation

    The findIndex() method of arrays is used to find the index of the first element in the array that satisfies the provided testing function. This is suitable for locating a specific to-do by its ID to then update it by its index.

  25. 25

    Which HTTP verb is used to remove a specific resource from the server?

    1. A

      The DELETE verb is specifically designed for deleting resources.

    2. B

      The PURGE verb is utilized for permanent removal.

    3. C

      The REMOVE verb is an alternative for resource deletion.

    4. D

      The CLEAR verb is dedicated to resource removal.

    Correct answer
    A

    The DELETE verb is specifically designed for deleting resources.

    Explanation

    The DELETE HTTP verb is the standard method used in RESTful APIs to request that the origin server delete the resource identified by the Request-URI.

  26. 26

    How can an array of to-do items be updated to remove a specific item based on its ID?

    1. A

      By assigning the array to array.filter(todo => todo.id !== id).

    2. B

      By using splice() on the original array directly.

    3. C

      By setting the element at the index to null or undefined.

    4. D

      By manually looping and removing the matching element.

    Correct answer
    A

    By assigning the array to array.filter(todo => todo.id !== id).

    Explanation

    To remove an item from an array and get a new array without that item, the filter() method is very effective. It creates a new array containing all elements for which the provided callback function returns true. By filtering for todo.id !== id, all items except the one with the specified ID are kept.

  27. 27

    What is the primary benefit of grouping routes into separate files (e.g., routes/todos.js)?

    1. A

      It improves code organization and maintainability for large applications.

    2. B

      It enforces stricter security protocols for API endpoints.

    3. C

      It allows for faster server startup times.

    4. D

      It enables automatic data validation for all route parameters.

    Correct answer
    A

    It improves code organization and maintainability for large applications.

    Explanation

    Grouping routes into separate files (like routes/todos.js) helps in organizing the codebase, especially as an application grows. This makes the index.js or main application file cleaner and improves maintainability by separating concerns.

  28. 28

    What is used in routes/todos.js instead of app to define individual routes within a modular file?

    1. A

      The router object obtained from express.Router().

    2. B

      The server object from the main application file.

    3. C

      A module object that is implicitly available.

    4. D

      An Endpoint instance specifically for this file.

    Correct answer
    A

    The router object obtained from express.Router().

    Explanation

    When structuring routes modularly, express.Router() is used to create a new router object. This object then behaves like a mini-application, allowing you to define route handlers using router.get(), router.post(), etc., instead of app.get(), app.post() directly.

  29. 29

    How do you make routes defined in a modular router available to the main Express app?

    1. A

      By directly assigning the router to app.routes property.

    2. B

      By including the router's file path in the package.json.

    3. C

      By calling app.mount(router) with the router object.

    4. D

      By importing the router with require() and then using app.use().

    Correct answer
    D

    By importing the router with require() and then using app.use().

    Explanation

    To integrate modular routers into the main Express application, you use app.use(). The first parameter to app.use() can be a base path, and the second is the router object imported via require(), making its routes available under the specified path.

  30. 30

    What is the function of the optional first string parameter in app.use('/todos', todoRoutes)?

    1. A

      It defines a unique name for the middleware or router being used.

    2. B

      It sets a common base path for all routes defined within todoRoutes.

    3. C

      It specifies the exact file path where the router is located.

    4. D

      It limits the router to only handle requests with a query parameter 'todos'.

    Correct answer
    B

    It sets a common base path for all routes defined within todoRoutes.

    Explanation

    When app.use() is called with a path as its first argument (e.g., '/todos'), it means that all routes defined within the todoRoutes router will be prefixed with /todos. This creates a common base path for the group of routes.

  31. 31

    What does 'middleware' refer to in the context of Express.js?

    1. A

      It is a database layer that sits between the application and data storage.

    2. B

      It is a templating engine used for rendering dynamic HTML content.

    3. C

      It is a tool for managing application state across different components.

    4. D

      It is code that executes before or after a request reaches a route handler.

    Correct answer
    D

    It is code that executes before or after a request reaches a route handler.

    Explanation

    Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. They can execute any code, make changes to the request and the response objects, end the request-response cycle, or call the next middleware in the stack. app.use(express.json()) is a prime example.

  32. 32

    Which parameter in a middleware function is used to pass control to the next middleware or route handler?

    1. A

      The pass parameter transfers control immediately.

    2. B

      The finish parameter is invoked to proceed.

    3. C

      The continue parameter signals the next step.

    4. D

      The next parameter is called to move forward in the chain.

    Correct answer
    D

    The next parameter is called to move forward in the chain.

    Explanation

    Middleware functions in Express take a third argument, next. Calling next() within a middleware function passes control to the next middleware function in the stack, or if there are no more middleware functions, to the route handler.

  33. 33

    How do you access custom data sent within the HTTP request headers in an Express middleware?

    1. A

      By calling req.query.headerName for the header data.

    2. B

      By checking req.params.headerName for the header value.

    3. C

      By accessing req.header('headerName') or req.headers['headerName'].

    4. D

      By using req.body.headerName to get the value.

    Correct answer
    C

    By accessing req.header('headerName') or req.headers['headerName'].

    Explanation

    The req.header() method (or direct access req.headers['header-name']) is used to retrieve values from the HTTP request headers. The example shows req.header('authenticated') to check for an authentication status.

  34. 34

    What HTTP status code typically indicates that a client's request is forbidden due to insufficient authorization?

    1. A

      Status code 403 (Forbidden) signifies a lack of permission.

    2. B

      Status code 400 (Bad Request) is used for forbidden access.

    3. C

      Status code 500 (Internal Server Error) indicates forbidden action.

    4. D

      Status code 200 (OK) implies unauthorized access.

    Correct answer
    A

    Status code 403 (Forbidden) signifies a lack of permission.

    Explanation

    The HTTP status code 403 Forbidden indicates that the server understood the request but refuses to authorize it. This typically means the client does not have the necessary permissions for the resource.

Question 1 of 34
Question 1 of 34

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent