NodeJs从服务器主动发送请求

从服务器主动发送请求

const http = require('http');
const path = require('path');
const fs = require('fs');

let options = {
	hostname: 'www.baidu.com',
	port: 80
}			
http.request(options, (res) => {
	let info = '';
	res.on('data', (chunk) => {
		info += chunk;
	});
	res.on('end', () => {
		fs.writeFile(path.join(__dirname, 'baidu.html'), info, (err) => {
			console.log('已经获取到百度主页的内容');
		});
	});
});
req.end();

从服务器主动发送请求调用后台接口1

const http = require('http');

let options = {
	protocol: 'http:',
	hostname: 'localhost',
	port: 3000,
	path: '/books'
}			
http.request(options, (res) => {
	let info = '';
	res.on('data', (chunk) => {
		info += chunk;
	});
	res.on('end', () => {
		console.log(info);
	});
});
req.end();	

从服务器主动发送请求调用后台接口2

const http = require('http');
const querystring = require('querystring');

let options = {
	protocol: 'http:',
	hostname: 'localhost',
	port: 3000,
	path: '/books/book',
	method: 'post',//请求方式
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded'
	}
}			
http.request(options, (res) => {
	let info = '';
	res.on('data', (chunk) => {
		info += chunk;
	});
	res.on('end', () => {
		console.log(info);
	});
});

let data = qureystring.stringify({
	name: 'ddd',
	author: 'ddd',
	category: 'ddd',
	desc: 'dsadfasdf'
});
req.write(data);
req.end();	

调用第三方接口-获取天气信息

const http = require('http');
				
let options = {
	protocol: 'http:',
	hostname: 'www.weather.com.cn',
	port: 80,
	path: '/data/sk/101010300.html',
	method: 'get'
}			
http.request(options, (res) => {
	let info = '';
	res.on('data', (chunk) => {
		info += chunk;
	});
	res.on('end', () => {
		console.log(info);
	});
});
req.end();	

以上是总结的示例代码。

Node.js结合WebSocket可以用来监听前端在线的状态。 WebSocket是一种在单个TCP连接上进行全双工通信的协议,它允许服务器主动向客户端推送数据,而不需要客户端发起请求。Node.js是基于JavaScript的开发平台,通过使用WebSocket模块可以实现WebSocket通信。 首先,我们需要在Node.js中创建一个WebSocket服务器。可以使用第三方库如ws或socket.io来帮助我们简化开发。通过安装相应的模块,并在代码中引入,我们可以创建一个WebSocket服务器的实例。然后,需要在服务器上设置监听端口,这样WebSocket服务器就可以接受来自前端的连接请求。 在前端,我们可以使用JavaScript的WebSocket API来与服务器建立WebSocket连接。通过指定服务器的地址和端口,前端可以向服务器发起连接请求。一旦建立连接成功,服务器和前端之间可以通过发送消息来实现实时通信。服务器可以监听前端的在线状态,前端也可以接收来自服务器的消息并作出相应的处理。 在Node.js中,可以使用WebSocket服务器的事件来监听前端的连接和断开连接。通过监听连接事件,我们可以记录前端的在线状态,比如在数据库或内存中将其标记为在线。而监听断开连接事件,可以更新前端的在线状态,将其标记为离线。 通过结合Node.js和WebSocket,我们可以实现实时的在线状态监听功能。服务器可以准确记录前端的在线状态,并根据需要做出相应的处理。前端可以实时接收来自服务器的消息,保持与服务器的通信。这样就可以实现前端在线的监听。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值