Node.js是一個(gè)JavaScript 的 runtime 環(huán)境,允許你在瀏覽器外執(zhí)行js代碼,提供了更多和文件系統(tǒng)交互的可能,比如讀寫本地文件,獲得計(jì)算機(jī)信息等。
有一些網(wǎng)站提供API交互,使你可以不通過普通用戶的使用方式(鍵鼠輸入,靠點(diǎn)擊在網(wǎng)頁內(nèi)容間跳轉(zhuǎn)等等),而是使用代碼直接和其互動(dòng),因此也有更多自動(dòng)化的可能。比如通過微博的API,寫一段代碼來自動(dòng)發(fā)布博文等。
以下是一個(gè)完整的JS文件,只有這幾行,如果你打開網(wǎng)站https://jsonplaceholder.typicode.com/todos,會(huì)看到一堆數(shù)據(jù),這段代碼就是用來得到/下載這一頁數(shù)據(jù)的。(這個(gè)網(wǎng)站的內(nèi)容沒有什么實(shí)際意義,人如其名jsonplaceholder,其創(chuàng)建的初衷就是用來發(fā)送一些無意義的JSON數(shù)據(jù)做展示用的)
這個(gè)https的URL就是我們API的endpoint(端點(diǎn))。
根據(jù)它們的網(wǎng)頁介紹 https://jsonplaceholder.typicode.com/,你可以使用的端點(diǎn)有:
| /posts | 100 posts |
| /comments | 500 comments |
| /albums | 100 albums |
| /photos | 5000 photos |
| /todos | 200 todos |
| /users | 10 users |
fetch不同的端點(diǎn),你會(huì)得到不同的數(shù)據(jù)。
const URL = "https://jsonplaceholder.typicode.com/todos";
fetch(URL)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.error(err));
這個(gè)網(wǎng)頁只是一個(gè)很簡單的不需要驗(yàn)證用戶身份(不需要賬號登錄)的例子,但很多時(shí)候你是需要賬號信息來交互的。
Outline是一個(gè)類似簡書這樣可以發(fā)文章的,面向小團(tuán)隊(duì)的類WIKI網(wǎng)站,提供API交互。
我現(xiàn)在想要試試怎么和它的API交互。
首先根據(jù)它們的文檔https://www.getoutline.com/developers,我需要在個(gè)人用戶設(shè)置里先創(chuàng)建API key,
然后構(gòu)建fetch的header,把API key輸入到Authorization里。
body部分是request的內(nèi)容,在文檔里我們可以看到很多類別的request例子,比如我們想要使用Retrieve a collection,

request samples 里的
{
"id": "497f6eca-6276-4993-bfeb-53cbbbba6f08"
}
即是我們fetch的body部分。
用JSON.stringify()加入。
這個(gè)request需要文章的id或shareID,這種一般都是document頁面URL的最后一段。
const fs = require("fs");
async function outlineRequest() {
console.log("Sending request...");
const response = await fetch(
"https://app.getoutline.com/api/documents.list",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer ol_api_tV0AwsFOBclRHIUWA9OYuLz******",
},
body: JSON.stringify({
shareId: "abe2b1b9-d302-4650-a57c-136e*****",
}),
}
);
const body = response.body;
const document = body.data;
const statusText = body.statusText;
console.log("----body");
console.log(body);
console.log("----response.json()");
j = await response.json();
console.log(j);
towrite = j.data.text;
console.log("-----towrite");
console.log(towrite);
fs.writeFileSync("./content_Test.txt", towrite);
}
outlineRequest();
用命令行運(yùn)行此JS
$ node getoutline.js
返回結(jié)果如下 (部分):
Sending request...
----body
ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
----response.json()
{
data: {
id: '7e71b7c3-4269-46a7-91df-2c24e05c3d46',
url: '/doc/hfdgh-Hpnq5GmOwc',
urlId: 'Hpnq5GmOwc',
title: 'hfdgh',
text: 'fghfdghfg\n' +
'\n' +
'fdghfd\n' +
'\n' +
'hfd\n' +
'\n' +
'h\n' +
'\n' +
'fh\n' +
'\n' +
‘text’部分即是我獲取的這篇文章的正文部分了,我可以通過json的語法獲取各部分內(nèi)容,寫入本地txt文檔。