0% found this document useful (0 votes)
10 views

Node 1

Uploaded by

Habimana Daniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Node 1

Uploaded by

Habimana Daniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

1. Question: Explain the differences between ES5 and ES6.

Why might you choose to use ES6 for


building a Node.js server?

o Answer: ES5 (ECMAScript 5) is the version of JavaScript that introduced features like
strict mode and JSON support. ES6 (ECMAScript 2015) introduced significant
enhancements such as arrow functions, let and const for variable declarations, template
literals, and classes. ES6 improves code readability and maintainability, making it easier
to write modern JavaScript applications. For building a Node.js server, ES6 can enhance
development efficiency and clarity.

2. Question: Write a code snippet to create a basic Express.js server that listens on port 4000 and
responds with "Welcome to My Server!" when the root endpoint (/) is accessed.

o Answer:

javascript

Copy code

import express from 'express';

const app = express();

const PORT = 4000;

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

res.send('Welcome to My Server!');

});

app.listen(PORT, () => {

console.log(`Server is running on http://localhost:${PORT}`);

});

3. Question: What are the purposes of the body-parser and cors middleware in an Express.js
application? Provide an example of how to use them.

o Answer: body-parser is middleware that parses incoming request bodies in a


middleware before your handlers, making it easier to work with data sent in JSON or
URL-encoded format. cors (Cross-Origin Resource Sharing) allows your server to accept
requests from different origins. Example usage:

javascript

Copy code
import bodyParser from 'body-parser';

import cors from 'cors';

app.use(cors());

app.use(bodyParser.json());

4. Question: Describe how you would set up a MySQL database connection in a Node.js
application. What parameters would you need to provide?

o Answer: To set up a MySQL connection, you would use a library like mysql2 and provide
parameters such as host, user, password, and database. Example:

javascript

Copy code

import mysql from 'mysql2';

const db = mysql.createConnection({

host: 'localhost',

user: 'root',

password: 'yourpassword',

database: 'mydatabase'

});

5. Question: Define RESTful APIs. List and explain the four primary HTTP methods used in RESTful
services.

o Answer: RESTful APIs (Representational State Transfer) are web services that follow REST
principles, enabling interaction between client and server via HTTP. The four primary
HTTP methods are:

 GET: Retrieve data from the server.

 POST: Send data to the server to create a new resource.

 PUT: Update an existing resource on the server.

 DELETE: Remove a resource from the server.

6. Question: Write a RESTful API endpoint in Express.js to create a new item in a MySQL database.
Include error handling in your code.

o Answer:
javascript

Copy code

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

const { name } = req.body;

db.query('INSERT INTO items (name) VALUES (?)', [name], (err, results) => {

if (err) {

return res.status(500).json({ error: err.message });

res.status(201).json({ id: results.insertId, name });

});

});

7. Question: How can you implement input validation in an Express.js application? Provide an
example of a validation library you might use.

o Answer: Input validation can be implemented using libraries like express-validator or Joi.
For example, using express-validator:

javascript

Copy code

import { body, validationResult } from 'express-validator';

app.post('/items', [

body('name').isString().notEmpty()

], (req, res) => {

const errors = validationResult(req);

if (!errors.isEmpty()) {

return res.status(400).json({ errors: errors.array() });

// Proceed with saving the item

});

8. Question: Explain what middleware is in the context of Express.js. Give two examples of
middleware you could implement in a Node.js application.
o Answer: Middleware in Express.js is a function that has access to the request and
response objects and can modify them or end the request-response cycle. Examples
include:

 Logging Middleware: Logs request details for debugging.

 Error Handling Middleware: Catches and processes errors that occur during
request processing.

9. Question: What is the significance of using appropriate HTTP status codes in API responses?
Provide examples of three status codes and their meanings.

o Answer: Appropriate HTTP status codes communicate the outcome of a request to the
client, indicating success or failure. Examples:

 200 OK: The request was successful.

 404 Not Found: The requested resource could not be found.

 500 Internal Server Error: A generic error occurred on the server.

10. Question: Suppose you want to log all incoming requests to your Express server. Write a
middleware function that logs the HTTP method and the URL of each request.

o Answer:

javascript

Copy code

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

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

next();

});

These questions and answers provide a comprehensive assessment of students' understanding of key
concepts related to Node.js, Express.js, and RESTful API development.

4o mini

Assessment Questions and Answers

1. Question: What is Node.js, and why is it popular for server-side development?

o Answer: Node.js is an open-source, cross-platform JavaScript runtime environment that


allows developers to run JavaScript on the server side. It is popular for its non-blocking,
event-driven architecture, which makes it efficient for handling multiple connections
simultaneously. Additionally, it uses JavaScript, enabling full-stack development with a
single language.

2. Question: Describe how to create a simple Express.js server. What are the basic steps?

o Answer: To create a simple Express.js server:

1. Initialize a new Node.js project using npm init -y.

2. Install Express with npm install express.

3. Create a new JavaScript file (e.g., server.js) and import Express.

4. Set up a basic server that listens on a specified port and responds to a request.

5. Start the server using node server.js.

3. Question: What is the purpose of middleware in Express.js? Provide an example.

o Answer: Middleware functions in Express.js are functions that have access to the
request and response objects. They can modify the request, end the request-response
cycle, or call the next middleware function. For example, a logging middleware might log
request details:

javascript

Copy code

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

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

next();

});

4. Question: How do you set up a MySQL database connection in a Node.js application? What
parameters are required?

o Answer: To set up a MySQL database connection in Node.js, you can use the mysql2
package. Required parameters typically include host, user, password, and database.
Example:

javascript

Copy code

import mysql from 'mysql2';

const db = mysql.createConnection({

host: 'localhost',
user: 'root',

password: 'yourpassword',

database: 'mydatabase'

});

5. Question: Define RESTful APIs and explain their importance.

o Answer: RESTful APIs (Representational State Transfer) are web services that follow the
principles of REST architecture. They allow clients to interact with server resources using
standard HTTP methods (GET, POST, PUT, DELETE). RESTful APIs are important because
they provide a stateless, scalable, and uniform interface for communication, making it
easier to build and maintain applications.

6. Question: Write a code snippet to create a RESTful API endpoint in Express.js that retrieves all
items from a MySQL database.

o Answer:

javascript

Copy code

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

db.query('SELECT * FROM items', (err, results) => {

if (err) {

return res.status(500).json({ error: err.message });

res.json(results);

});

});

7. Question: What are HTTP status codes, and why are they important in API development?

o Answer: HTTP status codes are standardized codes returned by a server to indicate the
result of an HTTP request. They are important in API development because they inform
the client about the success or failure of a request, helping clients understand how to
proceed based on the response. For example, a 200 status indicates success, while a 404
status indicates that a resource was not found.

8. Question: How can you handle errors in an Express.js application? Provide an example of an
error handling middleware.

o Answer: You can handle errors in Express.js by defining an error handling middleware.
This middleware captures any errors that occur during request processing. Example:
javascript

Copy code

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

console.error(err.stack);

res.status(500).send('Something went wrong!');

});

9. Question: What is input validation, and how can it be implemented in an Express.js application?

o Answer: Input validation is the process of checking incoming data to ensure it meets
certain criteria before processing it. It can be implemented in Express.js using libraries
like express-validator or Joi. For example, with express-validator:

javascript

Copy code

import { body, validationResult } from 'express-validator';

app.post('/items', [

body('name').isString().notEmpty()

], (req, res) => {

const errors = validationResult(req);

if (!errors.isEmpty()) {

return res.status(400).json({ errors: errors.array() });

// Proceed to create the item

});

10. Question: Explain the significance of using the CORS middleware in an Express.js application.

o Answer: CORS (Cross-Origin Resource Sharing) is a security feature that restricts web
applications running in one domain from making requests to resources in another
domain. In an Express.js application, using the CORS middleware allows you to specify
which domains can access your API, enabling cross-origin requests and enhancing
security. You can implement it easily by using the cors package:

javascript

Copy code
import cors from 'cors';

app.use(cors());

These questions and answers should provide a comprehensive assessment of students' understanding of
the key concepts related to Node.js, Express.js, and RESTful API development.

You might also like