Awt 3
Awt 3
3. Widely recognized as the most popular web framework for Node.js, Express.js has
earned its reputation as the de facto standard in the ecosystem.
Routing: Express.js provides a simple and organized way to handle different HTTP
requests and map them to specific actions.
Templating: Express.js provides a way to render HTML templates using data from your
application.
Easy to Learn: Express.js is easy to learn and use, even if you are new to Node.js.
Large Community: Express.js has a large and active community that provides support
and resources.
If you are looking for a framework to build web applications and APIs with Node.js,
Express.js is a great choice. It is easy to learn, use, and scale, and it provides
a robust set of features to help you build great applications.
////////////////////////////////////////////////////////////////////////////////
RESTFUL SERVICES
6. **State Transfer**: RESTful services transfer state between client and server in
the form of resource representations. Through these representations, clients and
servers communicate and exchange data, maintaining the statelessness principle of
REST architecture.
///////////////////////////////////////////////////////////////////////////////
Route Parameters
```javascript
// Define a route with a parameter
app.get('/users/:userId', (req, res) => {
// Access the value of the route parameter
const userId = req.params.userId;
// Utilize the userId in your application logic
res.send(`User ID: ${userId}`);
});
```
In this example:
- The route `/users/:userId` defines a route parameter named `userId`.
- When a request is made to a URL like `/users/123`, Express.js extracts the
value `123` from the URL and stores it in `req.params.userId`.
- You can then access the value of the route parameter `userId` within the
route handler function `(req, res) => {...}` using `req.params.userId`.
///////////////////////////////////////////////////////////////////////////////
**Purpose:** GET requests are used to retrieve data from a server. They are
typically used for fetching resources such as HTML pages, images, stylesheets,
scripts, or any other type of data.
2. **GET Requests**
- **HTTP Method:** GET is one of the HTTP methods defined in the HTTP protocol.
It is considered safe and idempotent, meaning it should not change the state of the
server and can be repeated without causing different effects on the server.
3. **In Express.js**
```javascript
// Define routes to handle GET requests
app.get('/', (req, res) => {
res.send('Hello World!');
});
These routes respond with different content when accessed with a GET request.
For example, accessing `/contact` will return "Contact", and accessing `/about`
will return "About page".
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
2. **HTTP Method:** PUT is one of the HTTP methods defined in the HTTP protocol. It
is idempotent, meaning that making the same request multiple times should have the
same effect as making it once. Thus, if the same PUT request is issued multiple
times, the state of the resource on the server should remain unchanged after each
request.
3. **Request Structure:**
- In a PUT request, the client sends a request to the server, specifying the
resource it wants to update and providing the new data for that resource in the
request body.
4. **Response:**
- The server responds to a PUT request with a status code indicating the
outcome of the request. Common status codes include 200 OK for a successful update,
201 Created for a successful creation of a new resource, or 204 No Content for a
successful update with no response body.
- The response may include additional information about the updated resource or
any changes made to it.
5. **Example Code:**
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
If the current middleware function does not end the request-response cycle, it
must call `next()` to pass control to the next middleware function. Otherwise, the
request will be left hanging.
```javascript
// Middleware function to log requests
app.use((req, res, next) => {
const logData = `${new Date().toISOString()} - ${req.method} ${req.url}\n`;
// Append log data to the log file
fs.appendFile('logFile.txt', logData, (err) => {
if (err) {
console.error('Error writing to log file:', err);
}
});
// Call the next middleware function
next();
});
```
///////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////