Node.js
让 JavaScript 跑出浏览器。
Node.js
这一课你将能做到
- 用 Node.js 写第一个 HTTP 服务器
- 用 Express 框架写 RESTful API
- 连接数据库并返回 JSON 数据
为什么要学
JavaScript 以前只能跑在浏览器里,操作 DOM、响应点击。Node.js 让 JavaScript 能跑在服务器上,写后端 API、操作文件、连接数据库。前后端都用 JS,技术栈统一。
人话:Node.js 是「翻译官」,让 JavaScript 能跟操作系统、数据库打交道。
先建立图像
// 浏览器里的 JS:操作 DOM
document.querySelector('#btn').addEventListener('click', () => {
alert(' clicked');
});
// Node.js 里的 JS:操作服务器
const http = require('http');
http.createServer((req, res) => {
res.end('Hello from server');
}).listen(3000);
运行后:
浏览器访问 http://localhost:3000
→ 显示 "Hello from server"
跟着做
步骤 1:第一个 HTTP 服务器
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('你好,Node.js!');
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
node server.js
步骤 2:路由处理
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const { pathname, query } = url.parse(req.url, true);
if (pathname === '/api/courses') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([
{ id: 1, title: 'HTML' },
{ id: 2, title: 'CSS' }
]));
} else if (pathname === '/api/user') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ name: query.name || '访客' }));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);
步骤 3:Express 框架(推荐)
原生 http 模块太啰嗦,Express 封装了常用功能。
npm init -y
npm install express
// app.js
const express = require('express');
const app = express();
// 中间件:解析 JSON 请求体
app.use(express.json());
// GET 请求
app.get('/api/courses', (req, res) => {
res.json([
{ id: 1, title: 'HTML' },
{ id: 2, title: 'CSS' }
]);
});
// POST 请求
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === '123456') {
res.json({ code: 0, data: { token: 'abc123' } });
} else {
res.json({ code: 1, msg: '用户名或密码错误' });
}
});
// 启动
app.listen(3000, () => {
console.log('Express 服务器运行在 http://localhost:3000');
});