vieyahn2017 / jsup

0 stars 1 forks source link

JS - console发送http请求 #19

Open vieyahn2017 opened 11 months ago

vieyahn2017 commented 11 months ago

在浏览器控制台发送http请求 https://blog.csdn.net/b229911288/article/details/108258219

vieyahn2017 commented 11 months ago

let an2_fetch = async function (url) {
        const response = await fetch(url);
        // const data = (await response.json()).data;
        const data = await response.json();
        return data;
    }
vieyahn2017 commented 11 months ago

调用函数也要是async函数

let analysis2 = async function() {

    var protocol = "http";
    const url_XXX = "://xxx/yyy/zzz" 

    var answerDetails = null;
    try {

        // answerDetails = XXX;
        answerDetails = await this.an2_fetch(protocol + url_XXX);
    } catch(e) {
        if (e.message == "Failed to fetch") {
            protocol = "https";
            answerDetails = await this.analysis2_fetch(protocol + url_XXX);
        } else {
            console.log(e);
            return;
        }
    }

}

否则报错

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

vieyahn2017 commented 11 months ago

fetch失败之,协议不匹配

raven.min.js:2 Mixed Content: The page at 'https://xxx' was loaded over HTTPS, but requested an insecure resource 'http://xxx'. This request has been blocked; the content must be served over HTTPS.

vieyahn2017 commented 11 months ago

又如 浏览器发送POST请求 https://blog.csdn.net/riant110/article/details/121973815

vieyahn2017 commented 11 months ago

如何拿到promise里的数据以及为什么会出现promise数据 https://blog.csdn.net/z2000ky/article/details/132115261

  1. 使用.then()方法

  2. 使用async/await语法

vieyahn2017 commented 11 months ago

await之前的使用


    this.sleep = function (time) {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve();
            }, time);
        });
    }

    this.autoanswer = async function (exams) {
        await this.sleep(500);
        for (var i=0,len=exams.length; i<len; i++)
        {
            try {
                var item = exams[i];
                console.log(item);
                item.node.click();
                await this.sleep(500);
                item.search();
                item.answer();
                await this.sleep(500);
            } catch(e) {
                console.log(e);
            }
        }
    }