【发布时间】:2019-12-03 20:22:06
【问题描述】:
我目前正在开发 Chrome 扩展程序。因为我预料到会遇到困难,所以我用 HTML 和 JS 制作了一个测试版,向 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),据我所知,它们是相等的。
【问题讨论】:
-
您是否在控制台中遇到任何错误?还是在扩展中?
-
不,我目前正在尝试使用 php 日志文件来解决这个问题,转储我发送的所有内容。
标签: javascript google-chrome google-chrome-extension request fetch