如何通过node.js http模块实现服务器与客户端的创建及完整示例代码?
- 内容介绍
- 文章标签
- 相关推荐
本文共计138个文字,预计阅读时间需要1分钟。
Node.js中的http模块提供了创建服务器和客户端的方法。以下是一个简单的示例,展示了如何使用http模块创建一个基本的HTTP服务器和客户端:
javascriptconst http=require('http');
// 创建HTTP服务器const server=http.createServer((req, res)=> { if (req.url==='/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, World!'); }});
// 监听3000端口server.listen(3000, ()=> { console.log('Server running at http://localhost:3000/');});
// 创建HTTP客户端const client=http.get('http://localhost:3000/', (res)=> { let data='';
res.on('data', (chunk)=> { data +=chunk; });
res.on('end', ()=> { console.log(data); });});
本文实例讲述了node.js使用www.baidu.com', function (res) { res.on('data', function (data) { console.log(data.toString()); }); });
希望本文所述对大家node.js程序设计有所帮助。
本文共计138个文字,预计阅读时间需要1分钟。
Node.js中的http模块提供了创建服务器和客户端的方法。以下是一个简单的示例,展示了如何使用http模块创建一个基本的HTTP服务器和客户端:
javascriptconst http=require('http');
// 创建HTTP服务器const server=http.createServer((req, res)=> { if (req.url==='/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, World!'); }});
// 监听3000端口server.listen(3000, ()=> { console.log('Server running at http://localhost:3000/');});
// 创建HTTP客户端const client=http.get('http://localhost:3000/', (res)=> { let data='';
res.on('data', (chunk)=> { data +=chunk; });
res.on('end', ()=> { console.log(data); });});
本文实例讲述了node.js使用www.baidu.com', function (res) { res.on('data', function (data) { console.log(data.toString()); }); });
希望本文所述对大家node.js程序设计有所帮助。

