javascript - 当我尝试在函数中执行此操作时无法返回链接
问题描述
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 种其他选项,但我无法让它工作。我是初学者,所以它可能很简单,但我做不到。
谢谢你的帮助。
解决方案
好吧,如果您的 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) )
;
});
推荐阅读
- javascript - 如何为`pipe`d ES6函数生成JSDoc
- android - 删除边界和按钮边框之间的空间
- django - FOREIGN KEY 约束在删除对象时失败
- c++ - 向后打印二进制数
- voip - Microsip 软件电话构建问题(无法打开文件“hid.lib”)
- python - 关于python模块的问题
- python - PDF.js 在第一次尝试时给出了 CORS 问题,但在努力刷新后它的工作正常,没有任何问题
- python - 我怎样才能得到 List.__gt__() func 的源实现
- quarkus - 如何知道端口是否开放以服务 Rest 请求?
- python - Python请求,如何发送没有“”的json请求