1

我有来自 ConvertAPI 的类似 JSON 响应:

{
   "ConversionCost":10,
   "Files":[
      {
         "FileName":"somefile_XXX.pdf",
         "FileExt":"pdf",
         "FileSize":63911,
         "FileId":"718cc1XXXXXXXXX5",
         "Url":"https://v2.convertapi.com/d/XXXXXXXXXXXXXXXXXXXXXXX/somefile_XXX.pdf"
      }
   ]
}

我试图在以下脚本中通过result.ConversionCost[0](工作正常)提取 ConversionCost:result.files[0].Url

let convertApi = ConvertApi.auth({secret: '<API_SECRET>'})
let elResult = document.getElementById('result')
let elResultLink = document.getElementById('resultLink')
let elUrl = document.getElementById('urlInput')
elResult.style.display = 'none'

// On file input change, start conversion
document.getElementById('convertBtn').addEventListener('click', async e => {
    elResult.style.display = 'none'
    document.documentElement.style.cursor = 'wait'
    try {

        // Converting web page to PDF file
        let params = convertApi.createParams()
        params.add('url', elUrl.value)
        params.add('FileName', 'The_FileName.pdf');
        params.add('LoadLazyContent', 'true');
        params.add('Zoom', '1.5');
        params.add('PageSize', 'a4');
        params.add('MarginTop', '0');
        params.add('MarginRight', '0');
        params.add('MarginBottom', '0');
        params.add('MarginLeft', '0');
        let result = await convertApi.convert('web', 'pdf', params)


        fetch('some_page.asp?id=315&initials=DDD&pdf_url=' + result.files[0].Url + '&ConversionCost= ' + result.ConversionCost[0]).then(function(response) {
          return response.json();
        }).then(function(data) {
          console.log(data);
        }).catch(function() {
          console.log("Booo");
        });

        // Showing link with the result file
        elResultLink.setAttribute('href', result.files[0].Url)
        elResultLink.innerText = result.files[0].Url
        elResult.style.display = 'block'

    } finally {
        document.documentElement.style.cursor = 'default'

    }
})

但这给了我控制台中的错误Uncaught (in promise) TypeError: Cannot read property '0' of undefined at HTMLButtonElement.<anonymous>

我读错了还是我错过了什么?.. 这里是 GitHub vor ConvertAPI JS:https ://github.com/ConvertAPI/convertapi-js

4

3 回答 3

1

result.ConversionCost 是 Number 类型,但您已将其用作数组

于 2021-06-12T10:40:28.530 回答
0

试试这个(代码未测试):

fetch('includes/save_user_welcomeletter_to_server.asp?id=315&initials=DDD&pdf_url=' + result.files[0].Url + '&pdf_ConversionCost= ' + result.ConversionCost)
.then(r => r.json())
.then(o => { 
    // Showing link with the result file
    elResultLink.setAttribute('href', o.files[0].Url)
    elResultLink.innerText = o.files[0].Url
    elResult.style.display = 'block'
    console.log(o.ConversionCost);
})
于 2021-06-14T06:52:49.443 回答
-1

根据您上面给出的回复,

名为 Files 的索引尝试使用result.Files[0].Url

也许它会起作用。:)

于 2021-06-12T10:41:06.847 回答