How to Create a REST API with JavaScript (Node.js & Express)
To create a REST API with JavaScript, you can use Node.js and the Express framework. Here are the steps to get started:\n\n1. Install Node.js: Download and install Node.js from the official website (https://nodejs.org/en/download/). This will also install npm (Node Package Manager) which you'll use to manage dependencies.\n\n2. Create a new project directory: Open your terminal or command prompt and create a new directory for your project.\n\n bash\n mkdir my-rest-api\n cd my-rest-api\n \n\n3. Initialize a new Node.js project: Run the following command to initialize a new Node.js project and create a package.json file.\n\n bash\n npm init -y\n \n\n4. Install Express: Install the Express framework by running the following command:\n\n bash\n npm install express\n \n\n5. Create an index.js file: Create a new file called index.js in your project directory.\n\n bash\n touch index.js\n \n\n6. Open index.js and add the following code:\n\n javascript\n const express = require('express');\n const app = express();\n const port = 3000;\n\n // Define your API routes here\n\n app.listen(port, () => {\n console.log(`Server is running on port ${port}`);\n });\n \n\n7. Define your API routes: Inside the index.js file, you can define your API routes using Express.\n\n javascript\n app.get('/api/hello', (req, res) => {\n res.json({ message: 'Hello, World!' });\n });\n \n\n This example creates a GET route at /api/hello that returns a JSON response with a message.\n\n8. Start the server: Run the following command to start your server:\n\n bash\n node index.js\n \n\n You should see the message "Server is running on port 3000" in the console, indicating that your server is running.\n\n9. Test your API: Open your browser or a tool like Postman and visit http://localhost:3000/api/hello. You should see the JSON response with the message "Hello, World!"\n\nCongratulations! You have created a basic REST API with JavaScript using Node.js and Express. From here, you can add more routes and logic to build your API according to your requirements.
原文地址: https://www.cveoy.top/t/topic/p1VK 著作权归作者所有。请勿转载和采集!