Fetch API & Async Await

Fetch API & Async Await



const fetchJSON = (url = ``) => {
return fetch(url,
{
method: "GET",
// mode: "no-cors",
mode: "cors",
credentials: "same-origin",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
})
.then(res => res.json())
.then(
(json) => {
return json;
}
)
.catch(err => console.log(`fetch error`, err));
}; // async / await
async function getDatas(url = ``) {
try {
return await fetchJSON(url);
} catch (err) {
console.error("getDatas error:\n", err);
}
} // demo const promiseData = getDatas(`https://cdn.xgqfrms.xyz/json/ssr/posts.json`); promiseData.then(data => console.log(`promiseData`, data));

Fetch API & Async Await


SSR


"use strict"; /**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-02-23
* @modified
*
* @description
* @augments
* @example
* @link
*
*/ const log = console.log; const puppeteer = require('puppeteer');
const handlebars = require('handlebars');
const fetch = require('node-fetch'); const fs = require('fs');
const path = require('path');
const util = require('util');
const readFile = util.promisify(fs.readFile); class Poster {
constructor(dom) {
this.dom = dom;
}
async fetchData(url) {
const data = await fetch(url).then(res => res.json());
// const data = await fetch(url).then(res => res.json()).catch(err => log(`fetch error`, err));
return data;
}
async html() {
try {
const data = {
timestamp: new Date().getTime(),
};
const templatePath = path.resolve('path', 'to', './poster-template.html');
const content = await readFile(templatePath, 'utf8');
// compile and render the template with handlebars
const template = handlebars.compile(content);
log(`template \n`, template);
return template(data);
} catch (error) {
throw new Error('Cannot create Poster HTML template.', error)
}
}
async screenshot() {
const html = await this.html();
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(html);
// await page.goto(url);
const screenshot = await page.screenshot({
path: 'poster-template-ssr.png',
fullPage: true,
});
await browser.close();
return screenshot;
}
}

上一篇:20145224&20145238 《信息安全系统设计基础》 第四次实验


下一篇:用jQuery实现优酷首页轮播图