返回
用 Node.js 的 http 模块创建最简单的 Web 服务器
后端
2023-10-26 04:23:10
1. 创建最简单的 Web 服务器
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!');
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
2. req 请求对象
const http = require('http');
const server = http.createServer((req, res) => {
console.log(req.method); // 请求方法
console.log(req.url); // 请求路径
console.log(req.headers); // 请求头
console.log(req.body); // 请求体
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!');
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
3. res 响应对象
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('Hello');
res.end('World!');
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
4. 根据不同的 url 响应不同的 html 内容
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World!</h1>');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>About Page</h1>');
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});