My geojson-file doesn't get loaded via fetch - leaflet

I am trying to load a geojson-file into my map via fetch right here
https://olive-highfalutin-crown.glitch.me/
but I get nothing shown to be loaded in my network sources.
That is my code therefore:
fetch("https://cdn.glitch.global/5778ed75-793f-41e9-810d-b244bbed9dbd/inkogym.geojson?v=1657180982175")
.then(function (response) {
return response.json();
})
.then(function (data) {
L.geoJSON(data).addTo(map);
});
Is my json not correct or what is the issue?

Related

display single record by id with vue js and axios

I have a mongodb express vue js app that displays a list of items in cards which are links to a detail view of each record. If I hover over the card the correct id for the link displays but click any card and it goes to the first document from mongo and the record does not display. The view retrieves an item but always the first one.
How to display a record of the ID of item clicked?
Report.vue
the backend request which works in postman is
// Get Simgle Report
router.get('/:id', async (req, res) => {
const reports = await loadReportsCollection()
await reports.findOne({_id: new mongodb.ObjectID( req.params.id)})
res.send(await reports.find({}).limit(1).toArray())
res.status(200).send()
}
)
ReportService.js looks like
//Find Single Report
static getReport(id) {
return axios.get(`${url}${id}`)
}
and the Report.vue file looks like
mounted () {
this.getReport()
},
methods: {
async getReport() {
try {
const response = await ReportService.getReport(this.$route.params.id)
this.report = response.data
} catch(err) {
this.err = err.message
}
},
}
many thanks for help!
It would seem you are trying to access a param in your api without passing one in your request. You ask for params here:
await reports.findOne({_id: new mongodb.ObjectID( req.params.id)})
but haven't passed any in your request. This should do it:
return axios.get('/:id', {
params: {
id: `${id}`
}
})
To not only get the first entry, but the one you are looking for you need to change your send() parameter.
Here is the working code:
// Get Simgle Report
router.get('/:id', async (req, res) => {
const reports = await loadReportsCollection()
const report = await reports.findOne({_id: new mongodb.ObjectID(req.params.id)})
res.send(await report)
res.status(200).send()
}
)
And as Andrew1325 stated you need to change your axios.get() call also to pass the correct params to it.

PWA Service worker match against specific cache timing issue

Fairly new to SW and Promises (and I'm not that good with JS either!) so I might be missing something obvious.
Users have different sections that they can add and delete and the sections contain images they would add to those sections so I want to use SW to cache those images but want to put them in a section numbered cache so if they delete a section I can easily just delete that cache.
Following some research and tutorials I got this working in the 'fetch' event listener:
var cacheName = `mycache-${id}`;
event.respondWith(
caches.match(event.request, { 'ignoreSearch': true }).then(function (resp) {
return resp || fetch(event.request).then(function (response) {
return caches.open(cacheName).then(function (cache) {
cache.put(event.request, response.clone());
return response;
})
})
})
);
But obviously that's searching all the caches so I assumed it would be more efficient to search the only cache it needs to however this doesn't seem to work, seems like it's hitting the fetch before it can respond with what it might have found in a cache?
var cacheName = `mycache-${id}`;
event.respondWith(
caches.open(cacheName).then(function (cache) {
console.log("Opened cache");
cache.match(event.request, { 'ignoreSearch': true }).then(function (resp) {
console.log("Tried to find a match");
return resp || fetch(event.request).then(function (response) {
return caches.open(cacheName).then(function (cache) {
cache.put(event.request, response.clone());
return response;
})
})
})
})
);
It is putting the images in the named cache so am I doing something stupid here, I understand that Promises are async but my understanding was the '.then' will wait for a response before it continues.
Ok well it appears it was a simple case of a missing return!
This line:
cache.match(event.request, { 'ignoreSearch': true }).then(function
(resp) {
should have been
return cache.match(event.request, { 'ignoreSearch': true
}).then(function (resp) {

Read file from GridFS based on _ID using mongoskin & nodejs

I am using mongoskin in my nodejs based application. I have used GridFS to uplaod the file. I am able to upload and read it back using the "filename" however I want to read it back using _id. How can i do? Following are code details.
Working code to read the file based on filename:
exports.previewFile = function (req, res) {
var contentId = req.params.contentid;
var gs = DBModule.db.gridStore('69316_103528209714703_155822_n.jpg', 'r');
gs.read(function (err, data) {
if (!err) {
res.setHeader('Content-Type', gs.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id '+contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};
How this code can be modified to make it work based on id?
After few hit & trial following code works. This is surprise bcz input parameter seems searching on all the fields.
//view file from database
exports.previewContent = function (req, res) {
var contentId = new DBModule.BSON.ObjectID(req.params.contentid);
console.log('Calling previewFile inside FileUploadService for content id ' + contentId);
var gs = DBModule.db.gridStore(contentId, 'r');
gs.read(function (err, data) {
if (!err) {
//res.setHeader('Content-Type', metadata.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id ' + contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};

In sails.js: fetch model's data from remote server

my sails.js app is embedded in php project where php generate some date for sails model. Can't find the way to fetch this date in beforeCreate callback or some custom method. I don't want use db to sync 2 models (model from sails & model from php). And i need to send some date to remote php app.
sails.js v.0.9.x
here is my controller:
module.exports = {
index: function (req, res) {},
create: function (req, res) {
if ( !req.param('login') )
throw new Error('Login is undefined');
if ( !req.param('message') )
throw new Error('Initial message is undefined');
var user, thread;
User.create({
id: 1,
name: req.param('login'),
ip: req.ip
}).done( function (err, model) {
user = model;
if (err) {
return res.redirect('/500', err);
}
user.fetch(); // my custom method
});
return res.view({ thread: thread });
}
};
and model:
module.exports = {
attributes: {
id: 'integer',
name: 'string',
ip: 'string',
fetch: function (url) {
var app = sails.express.app;
// suggest this but unlucky :)
app.get('/path/to/other/loc', function (req, res, next) {
console.log(req, res)
return next()
});
}
}
};
UPD My solution
Model:
beforeCreate: function (values, next) {
var options = 'http://localhost:1337/test',
get = require('http').get;
get(options, function (res) {
res.on('data', function (data) {
_.extend( values, JSON.parse( data.toString() ) );
next();
});
}).on('error', function () {
throw new Error('Unable to fetch remote data');
next();
});
}
Yikes--app.get is nowhere near what you need. That's binding a route handler inside of your app and has nothing to do with requesting remote data. Don't do this.
The easiest way to fetch remote data in Node is using the Request library. First install it in your project directory using npm install request. Then at the top of your model file:
var request = require('request');
and in your fetch method:
fetch: function(url, callback) {
request.get(url, function(error, response, body) {
return callback(error, body);
});
}
Note the added callback parameter for fetch; this is needed because the request is an asynchronous operation. That is, the call to fetch() will return immediately, but the request will take some time, and when it's done it will send the result back via the callback function. Seeing as fetch is at this point just a wrapper around request.get, I'm not sure why it's necessary to have it as a model method at all, but if the URL was based on something within the model instance then it would make sense.

confused with facebook json object with jquery and nodejs

writing my first facebook/node/express app
With express I'm using
app.post('/friends', function(req, res) {
graph.get("/me/friends?fields=id,name", function(err, res2) {
res.send(res2);
});
});
client side I'm using
$('#getFriends').click(function() {
$.post('/friends', function(data) {
console.log(data);
console.log(data.length);
});
});
With a previous app, I called the graph from the client side with getJSON and looped through everything with a for loop to print out the id and name. With this, I'm confused. Do I need to convert it to an array or a string first? Am I using the express request properly?
It logs the data object, but even when I go to print the length it's null.