how to fetch html content in js
same origin
CORS
fetch('https://cdn.xgqfrms.xyz/')
.then(function (response) {
// The API call was successful!
return response.text();
})
.then(function (html) {
// This is the HTML from our response as a text string
console.log(html);
})
.catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
fetch('https://www.cnblogs.com/xgqfrms/p/12818551.html')
.then(function (response) {
// The API call was successful!
return response.text();
})
.then(function (html) {
// This is the HTML from our response as a text string
console.log(html);
})
.catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
fetch('https://tianqi.moji.com/weather/china/shanghai/pudong-new-district', { mode: "no-cors", })
.then(function (response) {
// The API call was successful!
return response.text();
})
.then(function (html) {
// This is the HTML from our response as a text string
console.log(html);
})
.catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
bug ???
fetch("https://tianqi.moji.com/weather/china/guangdong/guangzhou", { mode: "no-cors", })
.then(res => {
console.log(`res =`, res)
return res.text();
})
.then(html => console.log(`html =`, html.toString()))
// res = Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}
// html =
fetch html
fetch("https://tianqi.moji.com/weather/china/shanghai/pudong-new-district", { mode: "no-cors", })
.then(res => {
console.log(`res =`, res)
return res.text();
})
.then(html => {
console.log(`html =`, html)
const parser = new DOMParser();
const dom = parser.parseFromString(html, "text/html");
console.log(`html dom =`, dom)
// api data
const todayWeather = dom.querySelectorAll(`.days`)[0].innerText.replace(/[
]/ig, `,`).split(`,`);
// ["今天", "阴", "21° / 30°", "南风", "4-5级", "55 良"]
console.log(`todayWeather api datas =`, todayWeather);
})
.catch(err => {
console.error('Failed to fetch html page content!', err);
});
https://stackoverflow.com/questions/36631762/returning-html-with-fetch
https://gomakethings.com/getting-html-with-fetch-in-vanilla-js/
SSR HTML page parser bug ???
not return html string ? blob
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!