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

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

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

31 questions

  1. 1

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

    Model answer

    npm init -y initializes a Node.js project by creating a package.json file with default values, which is essential for managing project metadata and dependencies.

    Explanation

    This command is the first step in setting up a new Node.js project. The -y flag tells npm to use default values for all prompts, quickly generating the package.json file without requiring user input. This file tracks project dependencies, scripts, and other metadata, making it crucial for any Node.js application.

  2. 2

    Which command is used to install the Express.js framework into a Node.js project?

    Model answer

    The command npm install express is used to install the Express.js framework.

    Explanation

    Express.js is the only direct dependency needed for building a basic REST API as demonstrated. npm install followed by the package name fetches the package from the npm registry and adds it to the project's node_modules directory and updates the package.json file.

  3. 3

    What is the typical file name convention for the main Express.js application file?

    Model answer

    The main Express.js application file is commonly named index.js or main.js.

    Explanation

    While the name can be arbitrary, index.js is a widely adopted convention for the primary entry point of many JavaScript applications, including those built with Express. This makes it easier for other developers to understand the project structure.

  4. 4

    Explain the role of app.listen(port, callback) in an Express.js application.

    Model answer

    app.listen() starts the Express server and makes it listen for incoming requests on a specified port, executing a callback function once the server is ready.

    Explanation

    This function is crucial for making the Express application accessible over a network. The port parameter (e.g., 3000) specifies which port the server should bind to, and the callback function is executed once the server successfully starts listening, often used for logging a message to the console.

  5. 5

    What happens if you navigate to localhost:3000 after starting an Express server with app.listen(3000) but without defining any routes?

    Model answer

    You will receive an error message in the browser, typically indicating that no route exists for the requested path.

    Explanation

    Express servers handle requests by matching them against defined routes. If no routes are defined, or if the root path / does not have a handler, the server cannot fulfill the request and will respond with a 'Cannot GET /' or similar error, as it doesn't know how to process the incoming request.

  6. 6

    How do you define a GET route for fetching all to-do items in Express.js?

    Model answer

    A GET route for fetching all to-do items is defined using app.get('/todos', (req, res) => { ... });.

    Explanation

    The app.get() method is used to handle HTTP GET requests. The first argument is the path (/todos), and the second is a callback function that receives the request (req) and response (res) objects. This route would be responsible for retrieving a collection of resources, such as all to-do items from a data source.

  7. 7

    What do the req and res parameters represent in an Express route handler callback?

    Model answer

    req represents the incoming HTTP request object, containing data from the client, while res represents the HTTP response object, used to send data back to the client.

    Explanation

    The req (request) object holds information about the incoming request, such as parameters, body, headers, and query strings. The res (response) object is used to build and send the HTTP response back to the client, including setting status codes, headers, and sending data (e.g., JSON, HTML).

  8. 8

    When should you use res.json() instead of res.send() in an Express route handler?

    Model answer

    res.json() should be used when sending JSON data as a response, as it automatically sets the Content-Type header to application/json and stringifies the object, whereas res.send() can send various types of responses.

    Explanation

    While res.send() is a more general-purpose method that can send strings, buffers, objects, or arrays, res.json() is specifically tailored for JSON responses. It ensures proper JSON formatting and sets the correct MIME type, which is crucial for REST APIs that primarily communicate using JSON.

  9. 9

    Why is it recommended to install nodemon globally (npm install nodemon -g) for development?

    Model answer

    nodemon is recommended for global installation in development to enable hot reloading of the Node.js application, automatically restarting the server when file changes are detected.

    Explanation

    During development, continuously stopping and restarting the server manually after every code change is inefficient. nodemon monitors for changes in your source files and automatically restarts the Node.js process, significantly speeding up the development workflow. Global installation makes it accessible from any project.

  10. 10

    How do you configure nodemon to run your Express application using an npm run dev script?

    Model answer

    In the package.json file, add a "dev": "nodemon index.js" entry under the scripts object, then run npm run dev.

    Explanation

    This setup allows you to execute nodemon index.js using a simpler npm run dev command. The scripts section in package.json defines custom commands, making it convenient to manage and run project-specific tasks like starting the development server with nodemon.

  11. 11

    What tool can be used to test various HTTP requests (GET, POST, PUT, DELETE) to an API without using the browser?

    Model answer

    Tools like Postman or Insomnia can be used to test various HTTP requests to an API.

    Explanation

    Browsers are typically limited to making GET requests. For testing other HTTP methods (POST, PUT, DELETE, etc.), or for sending custom headers and body data, dedicated API testing tools like Postman or Insomnia provide a user-friendly interface to construct and send requests, inspect responses, and manage collections of API calls.

  12. 12

    What HTTP verb is typically used for adding new data to a resource collection?

    Model answer

    The HTTP verb POST is typically used for adding new data to a resource collection.

    Explanation

    POST requests are designed to submit data to a specified resource, which often results in the creation of a new resource on the server. For example, creating a new to-do item would typically involve a POST request to the /todos endpoint with the new to-do's data in the request body.

  13. 13

    Why is app.use(express.json()) necessary for handling POST requests with JSON bodies in Express.js?

    Model answer

    app.use(express.json()) is necessary to parse incoming request bodies with JSON payloads, making the JSON data available on req.body.

    Explanation

    By default, Express does not parse the body of incoming requests. express.json() is a built-in middleware function that parses JSON data from the request body. Without it, req.body would be undefined, and the server would not be able to access the data sent by the client in a POST or PUT request.

  14. 14

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

    Model answer

    You can extract the title property using req.body.title or by destructuring it as const { title } = req.body;.

    Explanation

    After the express.json() middleware has parsed the request body, the parsed JSON object is attached to req.body. You can then access individual properties of this object using dot notation (req.body.title) or JavaScript's object destructuring syntax for a more concise way (const { title } = req.body;).

  15. 15

    What is the purpose of the uuid package and its v4 method in the context of creating new to-do items?

    Model answer

    The uuid package's v4 method generates universally unique identifiers (UUIDs) which are random, unique strings used as IDs for new to-do items, ensuring each item has a distinct identifier.

    Explanation

    When creating new records, it's essential to assign them a unique ID. uuid (specifically v4 which generates random UUIDs) provides a robust way to create these unique string identifiers. This prevents ID collisions, especially in a distributed environment, and simplifies operations like fetching or updating specific items.

  16. 16

    In a REST API, why is returning the newly added record in a POST request response considered good practice?

    Model answer

    Returning the newly added record in a POST request response is good practice because it provides the client with the final state of the resource, including any server-generated properties like its unique ID.

    Explanation

    When a client sends data to create a new resource, the server often adds properties like an ID, creation timestamp, or default values. Returning the complete, server-generated record allows the client to immediately update its local state with the authoritative version of the resource, making subsequent operations (like getting or updating that specific item) easier.

  17. 17

    How do you define a GET route to fetch a single to-do item by its ID using URL parameters in Express.js?

    Model answer

    A GET route to fetch a single to-do item by its ID is defined as app.get('/todos/:id', (req, res) => { ... });.

    Explanation

    The /:id segment in the path signifies a URL parameter. The colon (:) denotes that id is a placeholder for a dynamic value. When a request matches this route (e.g., /todos/123), the value '123' will be available in req.params.id.

  18. 18

    How do you access the id from the URL parameter in an Express route handler defined as '/todos/:id'?

    Model answer

    You access the id from the URL parameter using req.params.id or by destructuring it as const { id } = req.params;.

    Explanation

    The req.params object contains properties mapped to the named URL parameters defined in the route path. For a route like /todos/:id, a request to /todos/abc would result in req.params.id being 'abc'.

  19. 19

    Why is storing to-do items in a simple JavaScript array not suitable for data persistence across server restarts?

    Model answer

    Storing to-do items in a simple JavaScript array is not suitable for data persistence because the array's contents are lost every time the server restarts, as variables in memory are reset.

    Explanation

    In-memory data structures like arrays are volatile. When the Node.js process terminates (e.g., due to a code change, crash, or manual restart), all data held in application variables is cleared. To achieve persistence, data must be stored in a non-volatile medium like a database (e.g., MongoDB, PostgreSQL) or a file system.

  20. 20

    What HTTP verb is typically used for updating an existing resource, and why?

    Model answer

    The HTTP verb PUT is typically used for updating an existing resource because it represents a complete replacement of the resource at the specified URL.

    Explanation

    A PUT request is idempotent, meaning that making the same request multiple times will have the same effect as making it once. It's used to update an entire resource; the client sends a complete representation of the resource to be stored at the specified URI. While PATCH is for partial updates, PUT is for full replacements.

  21. 21

    How can you find the index of a specific to-do item in an array based on its ID?

    Model answer

    You can find the index of a specific to-do item using the findIndex() array method, like todos.findIndex(todo => todo.id === id);.

    Explanation

    The findIndex() method iterates over an array and returns the index of the first element for which the provided testing function returns true. If no elements satisfy the condition, it returns -1. This is useful when you need to directly modify an item in an array by its index.

  22. 22

    What is the typical HTTP verb used for deleting a resource?

    Model answer

    The HTTP verb DELETE is typically used for deleting a resource.

    Explanation

    A DELETE request is used to remove the specified resource. Similar to PUT, DELETE requests are also idempotent.

  23. 23

    How can you remove a specific to-do item from an array based on its ID without mutating the original array?

    Model answer

    You can remove a specific to-do item using the filter() array method, like todos = todos.filter(todo => todo.id !== id);, which creates a new array.

    Explanation

    The filter() method creates a new array with all elements that pass the test implemented by the provided function. By filtering out the to-do item whose id matches the one to be deleted, you effectively create a new array that excludes that item, without directly modifying the original array (though in the example, the todos variable is reassigned to the new filtered array).

  24. 24

    What is the primary benefit of organizing routes into separate files (e.g., routes/todos.js) using Express's Router?

    Model answer

    Organizing routes into separate files using Router improves code organization, modularity, and maintainability, especially for larger applications with many different resource types.

    Explanation

    As applications grow, having all route definitions in a single index.js file can become unmanageable. express.Router() allows you to create modular, mountable route handlers. Each file can manage routes for a specific resource (e.g., 'todos', 'animals'), making the codebase cleaner, easier to navigate, and more scalable.

  25. 25

    How do you create a modular router in Express.js for a specific set of routes?

    Model answer

    You create a modular router by importing Express and then invoking express.Router(), like const router = require('express').Router();.

    Explanation

    express.Router() creates a new router object. This object behaves like a mini-application, capable of defining its own middleware and routes. These routers can then be mounted on specific paths in the main application using app.use(), allowing for hierarchical route definitions.

  26. 26

    What is module.exports = router; used for in a todos.js route file?

    Model answer

    module.exports = router; is used to export the defined router object from todos.js, making it available for import and use in other files, such as index.js.

    Explanation

    In Node.js's CommonJS module system, module.exports specifies what a module exposes to other modules when it's require()d. By exporting the router instance, the main application file can then import and mount these modular routes.

  27. 27

    How do you integrate a modular router (e.g., todosRouter from routes/todos.js) into the main Express application (index.js)?

    Model answer

    You integrate a modular router using app.use('/todos', require('./routes/todos'));, where '/todos' is the base path for all routes defined in todos.js.

    Explanation

    The app.use() method, when given a path as its first argument and a router as its second, mounts the router at that specific base path. This means any route defined within the todosRouter (e.g., /) will now be accessible at /todos/. This avoids repeating the /todos prefix in every route within the todos.js file.

  28. 28

    Define 'middleware' in the context of Express.js and explain its typical execution flow.

    Model answer

    Middleware in Express.js is a function that has access to the request and response objects, and the next middleware function in the application's request-response cycle. It executes before the request reaches the final route handler.

    Explanation

    Middleware functions can perform various tasks: executing code, making changes to the request and response objects, ending the request-response cycle, or calling the next middleware function in the stack. They are executed in the order they are defined. A common use case is authentication, where middleware checks credentials before allowing the request to proceed to the intended route.

  29. 29

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

    Model answer

    The next() function in Express.js middleware is used to pass control to the next middleware function or route handler in the application's request-response cycle.

    Explanation

    If a middleware function does not end the request-response cycle (e.g., by sending a response), it must call next() to pass control to the next function. If next() is not called, the request will be left hanging, and subsequent middleware or the route handler will not be executed.

  30. 30

    How can you implement a simple authentication check using middleware that examines a request header?

    Model answer

    You can implement a simple authentication middleware by checking a specific request header using req.header('Authenticated'). If the header value is 'yes', call next(); otherwise, send a 403 Forbidden response.

    Explanation

    This example demonstrates how middleware can inspect incoming request properties (like headers) to make decisions. If the 'Authenticated' header is present and its value is 'yes', the request is allowed to proceed to the next middleware or route handler via next(). If not, a 403 Forbidden status is returned, preventing unauthorized access to subsequent resources.

  31. 31

    How do you apply a custom authentication middleware (checkAuth) to specific routes?

    Model answer

    You apply checkAuth middleware by including it as an argument between the route path and the route handler callback, like router.get('/', checkAuth, (req, res) => { ... });.

    Explanation

    Middleware functions can be added as arguments to route definitions. When a request matches this route, the checkAuth middleware will execute first. If checkAuth calls next(), then the final route handler callback will execute. This allows for granular control over which routes require specific processing, such as authentication.

1 of 31
Question 1 of 31

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent