从服务器主动发送请求
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();
以上是总结的示例代码。