首页 > 解决方案 > 当我尝试在函数中执行此操作时无法返回链接

问题描述

var image = document.getElementById('imageUpload');

image.addEventListener('change', event => {
    var imageData = event.target.files[0];
    imageUpload(imageData);
});


function main(text, image) {
    var text = document.getElementById('reportInput').value;
    if (image === '' || text === '') {
        alert('error');
    } else {
        console.log(text);
        // add here the upload image
    }
}

function apiToJson(link) {
    var parsingData = JSON.parse(link);
    console.log(parsingData.data.link);
}

function imageUpload(data) {

    var myHeaders = new Headers();
    myHeaders.append('Authorization', 'Client-ID 1a21bbf7bb87c77');

    var formdata = new FormData();
    formdata.append('image', data);

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: formdata,
        redirect: 'follow'
    }

    fetch("https://api.imgur.com/3/image", requestOptions)
        .then(response => response.text())
        .then(result => apiToJson(result))
        .catch(error => console.log('error', error));
}

这就是我的代码,主要功能连接到点击事件的html。当我 - console.log(parsingData.data.link); 在 apiToJson() 里面它的工作。而且我不知道如何在单击事件的主函数中获取 api 链接。我尝试了 50 种其他选项,但我无法让它工作。我是初学者,所以它可能很简单,但我做不到。

谢谢你的帮助。

标签: javascripthtml

解决方案


好吧,如果您的 API 使用 JSON 响应,那么就这样做

 return fetch("https://api.imgur.com/3/image", requestOptions)
.then(response => response.json())

接着

image.addEventListener('change', event => {
    var imageData = event.target.files[0];
    imageUpload(imageData)
    .then(json => console.log(json) )
    .catch( e => console.error(e) )
    ;
});


推荐阅读