I want to retrieve some data from my REST API in Node to the user directly downloaded in json file when he clicks a link.
I tried some stuff using Blop, but it is not working in my case I don't understand why...
HTML
<div class='wrapper_align_vertical'>
<a class='shortCut' id='extract'>Extract</a>
</div>
JS (sample that is working)
Viewed this example on internet and worked well with sample data.
document.getElementById('extract').onclick = function(event){
var data = { a: 1, b: "hello" }
var json = JSON.stringify(data)
var blob = new Blob([json], {type: "octet/stream"})
var url = window.URL.createObjectURL(blob)
this.href = url
this.target = '_blank'
// target filename
this.download = 'data.json'
}
But in my case I am calling API to gather data from database before creating the blop.
How I am getting data
I am calling the API with ajax request.
function getFromDB(){
return new Promise(function(resolve, reject){
$.ajax({
url: '/api/extract',
dataType: "json",
type: 'GET',
headers: {
"x-access-token" : getCookie('token')
},
success: function(data){
resolve(data)
}
})
})
}
What return the route /api/extract
The route get data from DB.
router.get('/', function(req, res, next){
var query = 'SELECT ...'
connection.query(query, function(err, rows){
var result = []
if(!err){
for(label in rows){
result.push(rows[label].path)
}
res.json({
success: true,
data:{
quantity : rows.length,
image: result
}
})
}else{
res.json({
success: false,
message: 'Failure while extracting tags from database !'
})
}
})
})
What I want to do
But it is absolutely not working, maybe I am missing something ?
document.getElementById('extract').onclick = function(event){
getFromDB()
.then(function(data){
var json = JSON.stringify(data)
var blob = new Blob([json], {type: "octet/stream"})
var url = window.URL.createObjectURL(blob)
this.href = url
this.target = '_blank'
this.download = 'data.json'
}, function(){
// Promise failed
})
}
If you have any advice or suggestion I'll appreciate, thank you !
Aucun commentaire:
Enregistrer un commentaire