您的位置:宽带测速网 > 网络知识 > nodejs如何获取网站内容

nodejs如何获取网站内容

2025-06-19 12:24来源:互联网 [ ]

要获取网站内容,可以使用Node.js中的http模块来发送HTTP请求。下面是一个使用http模块发送GET请求并获取网站内容的示例代码:

const http = require('http');const options = {hostname: 'example.com',port: 80,path: '/',method: 'GET'};const req = http.request(options, (res) => {let body = '';res.on('data', (chunk) => {body += chunk;});res.on('end', () => {console.log(body);});});req.on('error', (err) => {console.error(err);});req.end();

在代码中,options对象指定了要发送的请求的目标网站、端口、路径和请求方法。然后使用http.request()方法创建一个请求对象,并通过req.end()方法发送请求。在请求的回调函数中,通过监听data事件来获取响应的数据块,然后在end事件中将所有数据块组合起来,最后输出网站内容。

请注意,上述示例中的代码仅适用于HTTP协议。如果要获取HTTPS网站的内容,则需要使用https模块,并将端口号改为443。