Express.js 框架基础
开始使用 Express.js,搭建基本服务器并处理 HTTP 请求与响应。
Express.js 框架基础 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Discover Express.js
Express.js is a minimal and flexible Node.js web application framework.
It provides a robust set of features for web and mobile applications.
Think of it as a toolkit that simplifies building powerful server-side applications with Node.js.
Benefits of Express.js
Express.js makes backend development faster and easier. Here's why:
- Routing: Easily define how your app responds to different URLs.
- Middleware: Add functions that process requests before they reach your routes.
- Templating: Integrate with various templating engines for dynamic content.
- Performance: It's lightweight and fast, built on Node.js's non-blocking I/O.
Initialize Your Node.js Project
Before installing Express, you need a Node.js project. We'll use npm init to create a package.json file.
This file tracks your project's metadata and dependencies.
Open your terminal in an empty folder and run:
npm init -yThe -y flag answers "yes" to all prompts, creating a default package.json.
Add Express to Your Project
Now that your project is set up, let's install Express.js. NPM (Node Package Manager) handles this for us.
Run the following command in your project's terminal:
npm install expressThis command downloads Express and its dependencies, adding them to your node_modules folder and listing it in package.json.
Basic Server Setup
Every Express application starts by importing the Express module and creating an app instance.
This app object will be used to configure routes and start your server.
Let's see the basic structure:
const express = require('express');
const app = express();Handling HTTP GET Requests
Routes determine how your application responds to client requests to a specific endpoint (URL) and HTTP method (like GET, POST).
For a basic web page, we often use GET requests to retrieve data.
The app.get() method takes two arguments: the path (e.g., '/' for the homepage) and a callback function.
app.get('/', (req, res) => {
// Handle request and send response here
});Responding to Requests
Inside your route's callback function, you get two objects: req (request) and res (response).
The res object has methods to send responses back to the client. The simplest is res.send().
It can send various types of responses, like HTML, JSON, or plain text.
app.get('/', (req, res) => {
res.send('Hello from Express!');
});Making Your App Listen
Finally, your Express app needs to listen for incoming requests on a specific port.
The app.listen() method binds the application to a port on the local host. A common port for development is 3000.
Once running, you can access your app in a browser at http://localhost:3000.
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Run Your First Express App!
Here's a complete, runnable example of a basic Express server. Save this as app.js and run it with node app.js.
Then, visit http://localhost:3000 in your browser!
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Welcome to CoddyKit Express!');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});More Endpoints!
Your API won't just have one page! You can define multiple routes for different paths.
Each app.get(), app.post(), etc., creates a new endpoint.
Try adding an /about route to your app.js file.
app.get('/about', (req, res) => {
res.send('This is the About page.');
});Express Server Quiz
Consider the following Express.js code snippet:
const express = require('express');
const app = express();
const PORT = 5000;
app.get('/', (req, res) => {
res.send('Home Page');
});
app.get('/api', (req, res) => {
res.send({ message: 'API data' });
});
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});Express.js Foundations
Great job! You've learned the fundamentals of Express.js:
- What Express.js is and why it's useful.
- How to set up a Node.js project and install Express.
- Creating a basic Express application instance.
- Defining routes with
app.get(). - Sending responses with
res.send(). - Starting your server with
app.listen().
Next, we'll dive into more advanced routing and middleware concepts!
常见问题解答
「Express.js 框架基础」课时是免费的吗?
是的 — 「Express.js 框架基础」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「Express.js 框架基础」这节课中我会学到什么?
开始使用 Express.js,搭建基本服务器并处理 HTTP 请求与响应。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「Express.js 框架基础」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Express.js 框架基础
- Express 中的路由与中间件
- 设计 RESTful API 端点
- 处理请求数据:正文、查询与参数