Node.js是一个基于Chrome V8引擎的JavaScript运行环境,用于构建快速、可扩展的网络应用。
Node.js 特点
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
// 根据URL路由返回不同内容
if (req.url === '/') {
res.end('<h1>欢迎来到Node.js服务器</h1>');
} else if (req.url === '/about') {
res.end('<h1>关于我们</h1>');
} else {
res.writeHead(404);
res.end('<h1>页面未找到</h1>');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
提示: 这是一个重要的概念,需要特别注意理解和掌握。
注意: 这是一个常见的错误点,请避免犯同样的错误。