📜  expressjs hello world - Javascript (1)

📅  最后修改于: 2023-12-03 15:30:41.632000             🧑  作者: Mango

ExpressJS Hello World - JavaScript

Welcome to the introduction of ExpressJS, a popular web framework for JavaScript.

What is ExpressJS?

ExpressJS is a web application framework that allows you to build and run web applications using Node.js. It provides a way to structure your website or application, define the routes, and handle HTTP requests and responses.

Getting Started
Installation

Make sure you have Node.js installed on your system. You can then install ExpressJS using the following command:

npm install express
Hello World

Create a new file and add the following code to create a simple "Hello World" application.

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Example app listening on port 3000!');
});

In this code, we require the express module and create a new instance of the express object. We then define a route handler for the root URL. When a client makes a request to this URL, we respond with "Hello World!". Finally, we listen on port 3000 and log a message to the console.

Middleware

ExpressJS provides many built-in middleware functions that allow you to handle common tasks such as parsing HTTP request bodies, serving static files, and handling errors. You can also create custom middleware functions to perform any other specific tasks you need.

Here's an example of using middleware to log requests to the console:

const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Example app listening on port 3000!');
});

In this code, we define a middleware function that logs the request method and URL to the console. We then use the app.use() method to register this middleware function. The next() function is called to pass control to the next middleware function or route handler.

Conclusion

ExpressJS is a powerful and flexible web framework for JavaScript. It provides a range of features to help you build web applications with ease. In this article, we covered the basics of creating a "Hello World" application and using middleware. Be sure to explore the official documentation to learn more about what you can do with ExpressJS.