Node.js通过http模块实现HTTP服务器与客户端请求处理,支持GET、POST等请求类型,结合Express.js可简化开发。

Node.js处理HTTP请求的核心在于其内置的
http
Node.js的
http
const http = require('http');
const server = http.createServer((req, res) => {
// 处理请求
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});这段代码创建了一个监听3000端口的服务器。当有请求进来时,回调函数会被执行,设置响应头,并发送“Hello, Node.js!”作为响应体。
接下来,看看如何发起HTTP客户端请求:
const http = require('http');
const options = {
hostname: 'www.example.com',
port: 80,
path: '/',
method: 'GET'
};
const req = http.request(options, (res) => {
console.log(`状态码: ${res.statusCode}`);
res.on('data', (chunk) => {
console.log(`响应主体: ${chunk}`);
});
res.on('end', () => {
console.log('响应中已无数据。');
});
});
req.on('error', (error) => {
console.error(`请求遇到问题: ${error.message}`);
});
req.end();这段代码向
www.example.com
req.end()
不同的HTTP请求类型(GET, POST, PUT, DELETE等)需要不同的处理方式。对于GET请求,通常从URL中获取参数;对于POST请求,需要解析请求体中的数据。Node.js提供了多种方式来处理这些数据,例如使用
querystring
body-parser
例如,处理POST请求:
const http = require('http');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const postData = querystring.parse(body);
// 处理postData
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(postData));
});
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Only POST requests are accepted.');
}
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});这段代码监听POST请求,读取请求体,使用
querystring
处理HTTP错误和异常是健壮应用的关键。在服务器端,应该捕获可能出现的错误,并返回合适的HTTP状态码和错误信息。在客户端,应该处理请求失败的情况,例如网络错误或服务器返回错误状态码。
在服务器端,可以使用
try...catch
const http = require('http');
const server = http.createServer((req, res) => {
try {
// 可能会出错的代码
throw new Error('Something went wrong!');
} catch (error) {
console.error(error);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
}
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});在客户端,可以通过监听
error
const http = require('http');
const options = {
hostname: 'www.example.com',
port: 80,
path: '/nonexistent', // 故意请求一个不存在的路径
method: 'GET'
};
const req = http.request(options, (res) => {
console.log(`状态码: ${res.statusCode}`);
res.on('data', (chunk) => {
console.log(`响应主体: ${chunk}`);
});
res.on('end', () => {
console.log('响应中已无数据。');
});
});
req.on('error', (error) => {
console.error(`请求遇到问题: ${error.message}`);
});
req.end();虽然Node.js的
http
例如,使用Express.js创建一个简单的HTTP服务器:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express.js!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});这段代码使用Express.js创建了一个监听3000端口的服务器,并定义了一个处理GET请求的路由。相比直接使用
http
Express.js还提供了许多有用的中间件,例如
body-parser
cookie-parser
morgan
总的来说,Node.js的
http
以上就是怎样使用Node.js处理HTTP?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号