📅  最后修改于: 2023-12-03 15:14:57.212000             🧑  作者: Mango
In Javascript, Express is a popular web application framework that is used to build server-side applications. One of the most common tasks in web development is handling HTTP GET requests. In this guide, we will learn how to handle GET requests using Express.
Before getting started, make sure you have Node.js and Express.js installed on your machine. If not, you can install them by running the following command:
npm install express
Let's start by creating a basic Express server that handles a GET request. Create a new file called app.js
and add the following code:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In the above code, we first import the Express module and create a new Express application called app
. We then define a route for the root URL ("/") using the app.get
method. This method takes two arguments - the URL path and a callback function that handles the request and response objects. In this example, we simply send the string "Hello, World!" as the response.
Finally, we start the server by calling the app.listen
method and specifying the port number (in this case, 3000). Once the server is running, you can access it by navigating to http://localhost:3000
in your web browser.
Handling GET requests is a fundamental part of web development, and Express makes it easy to handle such requests in Javascript. In this guide, we learned how to create a basic Express server and handle a GET request. This is just the beginning - Express provides many more features for building robust web applications. For more information, refer to the official Express documentation.
Remember to always experiment and explore different ways to optimize and improve your Express applications. Happy coding!