March 18, 2024
O. Wolfson
Starting where we left off from the previous post about creating a basic Express server, we'll explore various Express server APIs that handle incoming data using the req object.
In the Express framework, incoming data is represented by the req object, short for "request". This object contains information about the incoming HTTP request made by the client to the server.
The incoming data contained in the req object can come from various sources depending on the type of request and how it's made. Here are some common sources of incoming data:
We'll create a route that responds with the value of the URL parameter.
Here's how you can do it:
bashnpm install express
index.js:bashtouch index.js
index.js in a text editor and add the following code:javascriptconst express = require("express");
const app = express();
// Define a route that takes a URL parameter
app.get("/users/:id", (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
// Start the server
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
In this example:
/users/:id, where :id is a placeholder for the user's ID.id parameter from the URL and stores it in req.params.id.bashnode index.js
Your server will now be running on port 3000.
http://localhost:3000/users/123, replacing 123 with any user ID you want to test with. You should receive a response indicating the user ID you provided in the URL parameter. For example, if you visit http://localhost:3000/users/123, you should see User ID: 123 as the response.That's it! You've created an Express server API that takes in a URL parameter. You can now expand upon this example to handle more complex scenarios or add additional routes and functionality as needed.
Create an Express server API that handles query parameters:
javascriptconst express = require("express");
const app = express();
// Define a route that handles query parameters
app.get("/search", (req, res) => {
const query = req.query.query;
res.send(`Search Query: ${query}`);
});
// Start the server
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
In this example:
/search to handle requests with query parameters./search?query=express), Express automatically parses the query parameters and makes them available in the req.query object.query parameter from req.query and send a response back to the client indicating the search query.To test the endpoint, you can make a GET request to http://localhost:3000/search?query=example, replacing example with any search query you want to test with. You should receive a response indicating the search query you provided in the query parameter. For example, if you visit http://localhost:3000/search?query=express, you should see Search Query: express as the response.
Here's a simple example of an Express server API that handles requests with a request body:
javascriptconst express = require("express");
const app = express();
// Middleware to parse JSON bodies
app.use(express.json());
// Define a route that handles POST requests with a JSON request body
app.post("/submit", (req, res) => {
const { name, email } = req.body;
res.send(`Submitted: Name - ${name}, Email - ${email}`);
});
// Start the server
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
In this example:
express.json() to our Express application. This middleware is used to parse incoming JSON requests./submit to handle POST requests.req.body object.name and email fields from the request body using object destructuring.To test the endpoint, you can make a POST request to http://localhost:3000/submit with a JSON request body. For example:
bashcurl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com"}' http://localhost:3000/submit
You should receive a response indicating the submitted data. For example:
bashSubmitted: Name - John Doe, Email - john@example.com
Here's a simple example of an Express server API that accesses request headers:
javascriptconst express = require("express");
const app = express();
// Define a route that handles GET requests
app.get("/headers", (req, res) => {
// Accessing request headers
const userAgent = req.headers["user-agent"];
const contentType = req.headers["content-type"];
// Sending response with headers information
res.send(`User-Agent: ${userAgent}, Content-Type: ${contentType}`);
});
// Start the server
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
In this example:
/headers to handle GET requests.req.headers.user-agent and content-type headers.To test the endpoint, you can make a GET request to http://localhost:3000/headers using cURL. You can use the following command:
bashcurl -H "Content-Type: application/json" http://localhost:3000/headers
You should receive a response containing information about the User-Agent and Content-Type headers.