Write a express js api
- User
Write a express js api
- Assistant
Write a express js api
Creating an Express.js API involves several steps including setting up a Node.js environment, installing Express.js, defining routes, and handling requests and responses. Below is a simple example of how to create a basic Express.js API that handles GET and POST requests.
Open your command line interface and run the following commands to create a new project directory and initialize it:
mkdir my-express-api
cd my-express-api
npm init -y
Now, install Express.js by running:
npm install express
Create a file named index.js in your project directory and add the following code to set up an Express server:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json()); // Middleware for JSON request parsing
// Define a simple GET route
app.get('/', (req, res) => {
res.send('Welcome to the Express.js API!');
});
// Define a POST route
app.post('/data', (req, res) => {
const data = req.body;
console.log(data); // Do something with the data
res.status(201).send({ message: 'Data received', receivedData: data });
});
// Start the server
app.listen(port, () => {
console.log(`Express.js server running at http://localhost:${port}`);
});
This code sets up an Express server that listens on port 3000 and has two routes: a GET route at the root (/) that sends a welcome message, and a POST route (/data) that accepts JSON data, prints it to the console, and sends back a confirmation along with the received data.
Back in the command line, start your server with the following command:
node index.js
You should see the message "Express.js server running at http://localhost:3000" in the console.
You can now test the API using an API client like Postman or by using curl commands in the terminal. Here's how you would test the GET and POST endpoints using curl:
Test the GET request:
curl http://localhost:3000/
And you'll see a response like:
Welcome to the Express.js API!
Test the POST request:
curl -X POST http://localhost:3000/data -H "Content-Type: application/json" -d '{"name": "John", "age": 30}'
And you'll see a response like:
{
"message": "Data received",
"receivedData": {
"name": "John",
"age": 30
}
}
You have now successfully created a basic Express.js API that can handle GET and POST requests. Expand upon this by adding more routes, middleware, error handling, and integrating a database as per your specific needs.