【问题标题】:How to get response value from fetch instead of a promise with no value?如何从 fetch 中获取响应值而不是没有值的 promise?
【发布时间】:2019-04-27 01:48:33
【问题描述】:

我正在构建一个 chrome 扩展来从页面中提取数据以从数据中构建一个 url,我希望将该 url 缩短为最终产品。在我的内容脚本文件中,我调用了一个 url 缩短器来压缩链接。我不断收到一个没有价值的承诺,崩溃会做出反应。在 devtools 中,我看到调用成功并返回了 url。

我尝试过异步等待,一个完整的异步功能,尝试强制response.toString()

这是相关的代码部分。

var listingInfo = new Map();    
listingInfo.set('Address', 'some standard address');    
var tinyLink = '(http://tinyurl.com)/api-create.php?url='; //() because I can't share shortener urls on this site.

/*-----------------------------------GET LINKS--------------------------*/

if(listingInfo.has('Address')){   var mapsLink = \`https://www.google.com/maps/place/${listingInfo.get('Address').replace(new RegExp(" ", "g"), '+')}\`;

  tinyLink = \`${tinyLink}${mapsLink} `;

  var dirLink = fetch(tinyLink, {
    method: "GET", 
    mode: "no-cors", 
    headers: {"Content-Type": "text/html"}   }).then((response)=>{
    return response;   });

  listingInfo.set('dirLink', dirLink); }

我希望收到一个纯文本字符串,因为在 devtools 的网络选项卡中,它显示了一个简单的字符串 url,而不是任何 JSON,但我不断收到 value="" 的已解决承诺。

【问题讨论】:

  • 我认为我的问题与 cors 相关,但还不了解僵局。

标签: javascript google-chrome-extension promise maps fetch


【解决方案1】:
// made this function to use XMLHttpRequest()
const setLink = (propName, url) => {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {

var link = xhr.responseText;
console.log(`link: '${link}'`);
listingInfo.set(propName, link);
}
}
xhr.send();
}

// Then called setLink()
if(listingInfo.has('Address')){
var mapsLink = 
`https://www.google.com/maps/place/${listingInfo.get('Address').replace(new 
RegExp(" ", "g"), '+')}`;

dirLink = `${tinyLink}${mapsLink}`;

console.log(dirLink);

setLink('dirLink', dirLink);
console.log(dirLink);


}

【讨论】:

    猜你喜欢
    • 2019-07-24
    • 2017-07-09
    • 2017-01-04
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2016-12-21
    • 1970-01-01
    相关资源
    最近更新 更多