相同的请求,不同的结果。 (Chrome扩展程序与Chrome浏览器)

时间:2019-12-03 20:22:06

标签: javascript google-chrome google-chrome-extension request fetch

我目前正在使用Chrome扩展程序。因为我预料到会有困难,所以我用HTML和JS制作了一个Beta版本,将请求发送到PHP脚本,该脚本可以正常工作。

尽管我只是复制并粘贴了我的代码(由于Chrome扩展程序的性质,做了一些小的更改),但是它不再起作用。该请求为JSON类型,包括priv_key和lv_number(及其键值)。

Beta版中的同一请求在扩展本身中产生不同的结果。

测试请求片段

function getFormData(data2submit) {
    event.preventDefault(); //Prevents Reload
    const status = document.getElementById("status"); // <p> to show status
    status.innerHTML="Request Sent";
    //get data that we need for the .json
    var privateKey = document.getElementById("PRIV-Key").value;
    var lv_number = document.getElementById("LV-Number").value;

    //create .json
    var formData = {
        "priv_key": privateKey,
        "lv_number": lv_number
    }

    //send data to sendFormData function
    sendFormData(JSON.stringify(formData));
}
function sendFormData(formData) {
    //function to send and receive data (and populate fields lateron)
    async function postData(formData) {
        const response = await fetch("http://localhost/learneasy_js/lCheck3.php", {
            method: 'POST',
            mode: "same-origin",
            credentials: "same-origin",
            headers: {
                'Content-Type': 'application/json'
            },
            referrer: 'no-referrer',
            body: formData
        });

        const json = await response.json();
    }
    postData(formData);
}

扩展请求片段

function sendRequest() {
  chrome.storage.sync.get(['key'], function(result) {
    privKey = deobfuscate(result.key);
  });

  chrome.storage.sync.get(['lvnr'], function(result) {
    lvnr = result.lvnr;
  });

  var formData = {
    "priv_key": privKey,
    "lv_number": lvnr
  }

  formData = JSON.stringify(formData);

  async function postData(formData) {
    const response = await fetch("http://localhost/learneasy_js/lCheck3.php", {
      method: 'POST',
      mode: "cors",
      credentials: "same-origin",
      headers: {
        'Content-Type': 'application/json'
      },
      referrer: 'no-referrer',
      body: formData
    });

    const json = await response.json();
    setInfo(json);

  }

  postData(formData);

}

我已经比较了两个主体(formData)的输出,据我所知,它们是相等的。

1 个答案:

答案 0 :(得分:0)

问题在于chrome.storage.sync.get是异步的,这意味着在将privKeylvnr变量设置为存储值之前,您正在使用它们,这是解决方法

function sendRequest() {
  chrome.storage.sync.get(['key', 'lvnr'], function(result) {
    var formData = {
      "priv_key": result.key,
      "lv_number": result.lvnr
    };
    postData(JSON.stringify(formData));
  });

  async function postData(formData) {
    const response = await fetch("http://localhost/learneasy_js/lCheck3.php", {
      method: 'POST',
      mode: "cors",
      credentials: "same-origin",
      headers: {
        'Content-Type': 'application/json'
      },
      referrer: 'no-referrer',
      body: formData
    });

    const json = await response.json();
    setInfo(json);
  }
}