我可以在Chrome控制台中使用此代码向localhost
上的URL发出发布请求:
fetch("http://localhost:50014/api/myapi/", {"credentials":"omit","headers":{"accept":"*/*","accept-language":"en-GB,en-US;q=0.9,en;q=0.8","cache-control":"no-cache","content-type":"application/json","pragma":"no-cache","sec-fetch-mode":"cors","sec-fetch-site":"cross-site","x-api-key":"abc123"},"referrerPolicy":"no-referrer","body":"{"nodeIds":["ABC123"]}","method":"POST","mode":"cors"});
我在开发人员工具中将此代码用作Chrome"片段",以尝试重复发出发布请求,出于某些测试目的,我试图识别错误:
while(1==1) {
fetch("http://localhost:50014/api/myapi/", {"credentials":"omit","headers":{"accept":"*/*","accept-language":"en-GB,en-US;q=0.9,en;q=0.8","cache-control":"no-cache","content-type":"application/json","pragma":"no-cache","sec-fetch-mode":"cors","sec-fetch-site":"cross-site","x-api-key":"abc123"},"referrerPolicy":"no-referrer","body":"{"nodeIds":["ABC123"]}","method":"POST","mode":"cors"});
setTimeout(() => { console.log("waiting"); }, 1000);
}
但是我从未看到 POST 请求生效,控制台中没有任何内容。为什么?
更新
谢谢@Jaromanda X。我更新到这个,但它仍然没有运行。为什么?
while(1==1){
callApi();
sleep(5000);
}
function callApi() {
fetch("http://localhost:50014/api/myapi/", {"credentials":"omit","headers":{"accept":"*/*","accept-language":"en-GB,en-US;q=0.9,en;q=0.8","cache-control":"no-cache","content-type":"application/json","pragma":"no-cache","sec-fetch-mode":"cors","sec-fetch-site":"cross-site","x-api-key":"abc123"},"referrerPolicy":"no-referrer","body":"{"nodeIds":["ABC123"]}","method":"POST","mode":"cors"});
}
function sleep(milliseconds) {
var currentTime = new Date().getTime();
while (currentTime + milliseconds >= new Date().getTime()) {
}
}
如果你想在一段时间后重复发出请求,你可以使用 setInterval,如下所示:
setInterval(()=>{
fetch("http://localhost:50014/api/myapi/", {"credentials":"omit","headers":{"accept":"*/*","accept-language":"en-GB,en-US;q=0.9,en;q=0.8","cache-control":"no-cache","content-type":"application/json","pragma":"no-cache","sec-fetch-mode":"cors","sec-fetch-site":"cross-site","x-api-key":"abc123"},"referrerPolicy":"no-referrer","body":"{"nodeIds":["ABC123"]}","method":"POST","mode":"cors"});
},5000)