0
点赞
收藏
分享

微信扫一扫

从服务器主动发送请求http.request(options[, callback])

624c95384278 2022-04-13 阅读 45
node.js

从服务器主动发送请求

从服务器主动发送请求调用接口-查询数据

const http = require('http');
//這是已知的并且已經存在的服務器 ---【獲取展示目錄下的頁面】
let option = {
	protocol:'http:',
	hostname:'localhost',
	port:3000,
	path:'/'
}
let req = http.request(option,(res)=>{
	let info = '';
	res.on('data',(chunk)=>{
		info += chunk;
	});
	res.on('end',()=>{
		console.log(info);
	})
});
req.end();

从服务器主动发送请求调用接口-添加数据

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

let options = {
	protocol:'http:',
	hostname:'localhost',
	port:3000,
	path:'/addBook',
	method:'post',
	headers:{
		'Content-Type': 'application/x-www-form-urlencoded'
	}
}



let req = http.request(options,(res)=>{
	let info = '';
	res.on('data',(chunk)=>{
		info += chunk;
	});
	res.on('end',()=>{
		console.log(info);
	})
});

let data = querystring.stringify({
	name:'wanger',
	author:'lisi123',
	category:'china story',
	desc:'abcdefghijkmnl'
});
req.write(data);
req.end();

从服务器主动发送请求调用接口-根据id去查询数据[返回是頁面]

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

let options = {
	protocol:'http:',
	hostname:'localhost',
	port:3000,
	path:'/toEditBook?id=3',
	method:'get'
}

let req = http.request(options,(res)=>{
	let info = '';
	res.on('data',(chunk)=>{
		info += chunk;
	});
	res.on('end',()=>{
		console.log(info);
	})
});
req.end();

从服务器主动发送请求调用接口-删除数据[put delete请求基本一样]

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

let options = {
	protocol:'http:',
	hostname:'localhost',
	port:3000,
	path : '/books/book/34',
	method : 'delete'
}

let req = http.request(options,(res)=>{
    let info = '';

    res.on('data',(chunk)=>{
        info += chunk;
    });
    res.on('end',()=>{
        console.log(info);
    });
});

req.end();

从服务器主动发送请求

http.request(options[, callback])

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

let options = {
	hostname:"www.baidu.com",
	port:80
}

let req = http.request(options,(res)=>{
	let info = '';
	res.on('data',(chunk)=>{
		info += chunk;
	});
	res.on('end',()=>{
		console.log(info);
		fs.writeFile(path.join(__dirname,'baidu.html'),info,(error)=>{
			console.log('成功获取百度主页内容');
		})
	})
});
req.end();
举报

相关推荐

0 条评论