Node.js发起http
Node.js发起http
HTTPS Module
HTTP 自带
Node.js 在标准库中带有 https 模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const chalk = require("chalk")
const https = require('https')
https.get('https://api.juejin.cn/tag_api/v1/query_category_briefs', res => {
let list = [];
res.on('data', chunk => {
list.push(chunk);
});
res.on('end', () => {
const { data } = JSON.parse(Buffer.concat(list).toString());
data.forEach(item => {
console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`);
})
});
}).on('error', err => {
console.log('Error: ', err.message);
});
Axios
Axios 是一个非常流行且受欢迎的 Promise 式请求库,可用于浏览器和 Node.js 环境;有着拦截器,数据自动转换 JSON 等十分方便的功能。
1
npm install axios
GET
不带参数
通过 axios 获取掘金板块分类简单示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
const chalk = require("chalk")
const axios = require('axios');
axios.get('https://api.juejin.cn/tag_api/v1/query_category_briefs')
.then(res => {
const { data } = res.data
data.forEach(item => {
console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`);
})
})
.catch(err => {
console.log('Error: ', err.message);
});
带参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function digitalassetlinks(domain, applicationId, cert) {
if (!domain.startsWith("https://")) {
domain = "https://" + domain;
}
// 定义要发送的参数
const params = {
'source.web.site': domain.trim(),
'relation': 'delegate_permission/common.handle_all_urls'.trim(),
'target.android_app.package_name': applicationId.trim(),
'target.android_app.certificate.sha256_fingerprint': cert.trim()
};
console.table(params);
axios({
method: "GET",
url: "https://digitalassetlinks.googleapis.com/v1/assetlinks:check",// 使用代理后的 apis
params: params
})
.then((response) => {
console.log("请求成功", response);
const data = response.data
data['linked'] ? alert('验证成功') : alert('验证失败');
})
.catch((err) => {
console.log("请求失败", err);
});
}
node-fetch
这个请求库它的 api 与 window.fetch 保持了一致,也是 promise 式的。最近非常受欢迎,但可能最大的问题是,它的 v2 与 v3 版差异比较大,v2 保持着 cjs 标准,而 v3 则用了 ejs 的方式
1
npm i -S node-fetch@2.6.7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const chalk = require("chalk")
const fetch = require("node-fetch")
fetch('https://api.juejin.cn/tag_api/v1/query_category_briefs', {
method: 'GET'
})
.then(async res => {
let { data } = await res.json()
data.forEach(item => {
console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`);
})
})
.catch(err => {
console.log('Error: ', err.message);
});
本文由作者按照 CC BY 4.0 进行授权