I want to sent the image as base64 code to google sheet by using fetch,but when I run my code it will shows error "data_sent is not defined".
I want to know where is the problem and how to fix it.
*image is the variable to save the image builded by canvas, image_data is the variable to save the base64 from image
this.saveAsImg = function() {
var image = new Image();
image.src = this.canvas.toDataURL("image/png");
if (image.src == this.emptyCanvas) {
alert('請先書寫')
} else {
console.log('提交的內容===>', image.src)
}
return image.src;
};
var image_data;
document.getElementById('save').onclick = function() {
image_data = writeCanvas.saveAsImg();
};
function post_trigger(image_data, uuid) {
let url = 'localhost:5050';
let data_sent = image_data;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: data_sent
//deviceID: uuid
})
}).then((response) => {
return response.json();
}).then((jsonData) => {
console.log(jsonData);
}).catch((err) => {
console.log('錯誤:', err);
})
}
document.getElementById('save').onclick = post_trigger(image, uuid);
I changed my code and here is the new code. It can connect to api and post Data URI successfully.
let post_trigger = document.getElementById('sent');
post_trigger.addEventListener('click', async function() {
let url = 'http://127.0.0.1:5000/test2';
let formData = new FormData();
formData.append("email", str);
let result = await fetch(url, {
method: 'post',
body: JSON.stringify({
uri: str
}),
headers: {
'content-type': 'application/json'
},
}).then(res => {
return res.text();
})
alert(result);
})