0% found this document useful (0 votes)
36 views11 pages

We Practice Questions

Uploaded by

Ayesha Asad
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)
36 views11 pages

We Practice Questions

Uploaded by

Ayesha Asad
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/ 11

Question 1

Create a simple Express.js server with a single route that responds with "Hello, World!" when
accessed via a GET request.

Set up an Express.js server.

Define a single route (/) that responds with "Hello, World!" when accessed.

Code:

const express = require('express');

const app = express();

const port = 3000;

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

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

});

app.listen(port, () => {

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

});

Question 2

Create an Express.js route that responds with a JSON object containing a list of users when accessed
via a GET request.

Define a route (/users) that responds with a JSON object containing a list of users.

Code:

const express = require('express');

const app = express();

const port = 3000;

const users = [

{ id: 1, name: 'Alice' },

{ id: 2, name: 'Bob' },


{ id: 3, name: 'Charlie' }

];

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

res.json(users);

});

app.listen(port, () => {

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

});

Question 3

Create an Express.js route that allows a user to submit their name via a POST request and responds
with a greeting message that includes their name.

Set up body parsing middleware to handle JSON data.

Define a route (/greet) that accepts a POST request with a JSON body containing a user's name.

Respond with a greeting message that includes the submitted name.

Code:

const express = require('express');

const app = express();

const port = 3000;

// Middleware to parse JSON bodies

app.use(express.json());

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

const name = req.body.name;

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

});
app.listen(port, () => {

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

});

Question 4

Create an Express.js route that accepts a user ID as a URL parameter and responds with the user's
information if the ID exists, or a 404 error if it doesn't.

Define a route (/users/:id) that accepts a URL parameter for the user ID.

Respond with the user's information if the ID exists, otherwise respond with a 404 error.

Code:

const express = require('express');

const app = express();

const port = 3000;

const users = [

{ id: 1, name: 'Alice' },

{ id: 2, name: 'Bob' },

{ id: 3, name: 'Charlie' }

];

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

const userId = parseInt(req.params.id);

const user = users.find(u => u.id === userId);

if (user) {

res.json(user);

} else {

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

});
app.listen(port, () => {

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

});

Question 5

Create an Express.js route that allows users to update their name via a PUT request. The request
should include the user ID as a URL parameter and the new name in the request body.

Set up body parsing middleware to handle JSON data.

Define a route (/users/:id) that accepts a PUT request with a URL parameter for the user ID and a
JSON body containing the new name.

Update the user's name if the ID exists, otherwise respond with a 404 error.

Code:

const express = require('express');

const app = express();

const port = 3000;

// Middleware to parse JSON bodies

app.use(express.json());

let users = [

{ id: 1, name: 'Alice' },

{ id: 2, name: 'Bob' },

{ id: 3, name: 'Charlie' }

];

app.put('/users/:id', (req, res) => {

const userId = parseInt(req.params.id);

const newName = req.body.name;

const userIndex = users.findIndex(u => u.id === userId);


if (userIndex !== -1) {

users[userIndex].name = newName;

res.send(`User ${userId} updated to ${newName}`);

} else {

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

});

app.listen(port, () => {

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

});

Connection of two files:


data.js file, assuming it contains an array of users or orders that you might use in an Express.js
application for demonstration purposes. I'll create a basic data.js file with some sample data and then
show you how to use it in your Express.js routes.

data.js
// Sample data file containing users and orders

// Array of user objects

const users = [

{ id: 1, username: 'alice', email: '[email protected]' },

{ id: 2, username: 'bob', email: '[email protected]' },

{ id: 3, username: 'charlie', email: '[email protected]' }

];

// Array of order objects

const orders = [
{ id: 1, userId: 1, item: 'Laptop', quantity: 1 },

{ id: 2, userId: 2, item: 'Phone', quantity: 2 },

{ id: 3, userId: 3, item: 'Book', quantity: 3 }

];

module.exports = { users, orders };

server.js
Here's how you can set up an Express.js server to use the data from data.js:

const express = require('express');

const app = express();

const port = 3000;

// Import the sample data from data.js

const { users, orders } = require('./data');

// Middleware to parse JSON bodies

app.use(express.json());

// Route to get all users

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

res.json(users);

});

// Route to get all orders

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

res.json(orders);

});

// Route to get a specific user by ID


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

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

const user = users.find(u => u.id === userId);

if (user) {

res.json(user);

} else {

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

});

// Route to get a specific order by ID

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

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

const order = orders.find(o => o.id === orderId);

if (order) {

res.json(order);

} else {

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

});

// Route to create a new user

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

const newUser = {

id: users.length + 1,

username: req.body.username,

email: req.body.email

};

users.push(newUser);
res.status(201).json(newUser);

});

// Route to create a new order

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

const newOrder = {

id: orders.length + 1,

userId: req.body.userId,

item: req.body.item,

quantity: req.body.quantity

};

orders.push(newOrder);

res.status(201).json(newOrder);

});

// Route to update a user by ID

app.put('/users/:id', (req, res) => {

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

const userIndex = users.findIndex(u => u.id === userId);

if (userIndex !== -1) {

users[userIndex] = {

id: userId,

username: req.body.username,

email: req.body.email

};

res.json(users[userIndex]);

} else {

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

}
});

// Route to update an order by ID

app.put('/orders/:id', (req, res) => {

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

const orderIndex = orders.findIndex(o => o.id === orderId);

if (orderIndex !== -1) {

orders[orderIndex] = {

id: orderId,

userId: req.body.userId,

item: req.body.item,

quantity: req.body.quantity

};

res.json(orders[orderIndex]);

} else {

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

});

// Route to delete a user by ID

app.delete('/users/:id', (req, res) => {

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

const userIndex = users.findIndex(u => u.id === userId);

if (userIndex !== -1) {

users.splice(userIndex, 1);

res.status(204).send();

} else {

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

}
});

// Route to delete an order by ID

app.delete('/orders/:id', (req, res) => {

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

const orderIndex = orders.findIndex(o => o.id === orderId);

if (orderIndex !== -1) {

orders.splice(orderIndex, 1);

res.status(204).send();

} else {

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

});

app.listen(port, () => {

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

});

Instructions

1. Create the data.js file:


2. Create a new file named data.js in your project directory.
3. Copy and paste the provided code for data.js into this file.
4. Create the server.js file:
5. Create a new file named server.js in your project directory.
6. Copy and paste the provided code for server.js into this file.
7. Install Express.js:
8. Open a terminal in your project directory and run the following command to install Express.js:

npm install express

Run the Server:

In the terminal, start your server by running:

node server.js
The server will start and listen on port 3000. You should see a message in the terminal: Server is running
on http://localhost:3000.

You might also like