Passing client data into url express routes - javascript

I am new to Node/Express, but I am converting my jQuery/Bootstrap app into an app with a node backend for routing and other server side tasks. Currently when a user clicks on a link, it will pass data into the url that I then grab when I get to the new page. Like this:
$("#parking_icon").on("click", function() {
window.location = "_views/parkingLot.html?37.415912?-121.897520";
});
I then grab and use that data on my parkingLot.html page. Like this:
var urlQuery = window.location.search.substring(1);
var mapLatLon = urlQuery.split("?");
var centerCoords = [parseFloat(mapLatLon[1]), parseFloat(mapLatLon[0])];
Now that I am trying to convert to using express routes, I am not exactly sure how to accomplish this. (I have about 20 buttons similar to the one above that all pass different coordinates in). I know I could accomplish this by creating a separate route for each of them similar to this:
app.get('/parkingLot?37.415912?-121.897520', function(req, res) {
res.render('parkingLot', {
title: 'testing ParkingLotPage'
});
});
But it seems like there has to be an easier way. Should I not be using an app.get() at all? I am sure this is a noob question so please forgive me, as I am new to working with Node/Express. I am using the ejs templating engine if that makes any difference.

Think a little more abstractly, if you have a route for /parkinglot with a query string, then we can work with that query string directly on the route.
app.get('/parkinglot', (req, res) => {
let lat = req.query.lat;
let long = req.query.long;
res.render('parkinglot', {
title: '',
data: {
lat: lat,
long: long
}
});
});
Make sure you're properly constructing your query string with the key=value syntax beginning with ? and all Key-Value pairs separated by an &
$("#parking_icon").on("click", function() {
window.location = "_views/parkingLot?lat=37.415912&long=-121.897520";
});

Related

Let Strapi CMS create pages based on html template file

So probably my explanation is awful, but i really don’t know how to express my problem or what to search for.
I got a site (www.example.com/blog.html) showing all blog post entries created in a headless cms (Strapi). The site receives the posts by making an url request and parsing the resulting JSON data. This data also contains an unique url slug for each post serving as an identifier.
I want to create one page for each blog post created in the headless cms based on a „template“ html.
What I tried is passing the urlslug as a url parameter (www.example.com/blog/article.html?id=*URLSLUG*) and then using this url parameter to fetch the corresponding post data from the cms. I followed this guide: https://strapi.io/blog/build-an-editorial-website-with-vanilla-java-script-and-strapi
It works, but I don’t want to rely on url parameters for seo reasons. Instead I want something like www.example.com/blog/*URLSLUG*. In other words: I want to have one page for each blog post entry in my headless cms based on a „template“ html.
Any suggestions?
Code can be added if necessary
well there is few options here:
The first one is most reliable, and easy but seems not that fancy as you want:
https://market.strapi.io/plugins/strapi-plugin-slugify
The main reason to use this solution is that it handles slug creation when you create post via REST api. The uuid field needs extra work when post created not from admin panel.
So second option is do it yourself style:
/api/article/controller/article.js
module.exports = createCoreController('api::article.article', ({strapi}) => ({
findOne(ctx){
const { slug } = ctx.params;
return strapi.db.query('api::article.article').findOne({where: {slug});
}
});
then in the routes create routes.js file
/api/article/routes/routes.js
module.exports = {
routes: [
{
method: 'GET',
path: '/articles/:slug'
handler: 'article.findOne'
}
]
}
then if you want to create articles for outside of admin, create lifecycles.js in
/api/article/content-types/article/lifecycles.js
module.exports = {
async beforeCreate(event) {
// here you have to do something like
let slug = slugify(event.result.name);
let isNotFree = await strapi.db.query("api::article.article").findOne({where: {slug}});
if (Boolean(!isNotFree)) // < not sure prolly need an empty object check
for (let i = 1; i < 9999 ; i++) {
slug = `${slug}-${i}`;
isNotFree = await strapi.db.query("api::article.article").findOne({where: {slug}});
if (Boolean(!isNotFree))
break;
}
event.result.slug = slug
}
}
pleas note the lifecycle code is just a first thing came to my mind, should be tested and optimized prolly
the implementation gives you the findOne controller, you gonna need to do it for each other update, delete, etc...

Express routing to search results

Got a real newbie question here. So i'm building an events page in which I'd like to filter results by date input (standard html form). I've made this a get request with the following routing:
app.get("/eventByDate/:date", async (req, res) => {
const d = req.params.date;
const data = await Event.find({ date: d });
if (data) {
res.render(`./events/eventByDate`, { data });
} else {
console.log("THERE IS NO DATA");
}
});
EventByDate is its own page, and I can access the relevant stuff by manually typing, for example, http://localhost:3000/eventByDate/2021-01-20
But as it is just now, the form submit takes me there but with the query string in the title, i.e. http://localhost:3000/eventByDate/?date=2021-01-20
Does anyone have a solution to this? My initial idea was to try to remove the query string but this seems a little inelegant, so I'm sure there is a simpler way that I'm completely missing?
Thanks in advance.

Mongodb-Rest queries with like [duplicate]

My question is simple but i can not find exact solution. All articles have gor below a line of code:
collection.findOne({hello:'world_no_safe'});
Above codes does work and returns to me undefined error.But it is existed. Anyway, My exact solution is above. Please help me and teach me how to use regex by searching inside of the json api. ı want to use %mysearch data% as a regex expression. ı want to make text search which is used all sentences in json.
For example : i have a json:
[{"data":"Andreas Kollegger explains what kinds of questions you can answer with a graph database. It's not only the big sites that "},{"data":"X explains what kinds of questions you can answer with a graph database. It's not only the big sites that "}]
if i use this expression: collection.findOne({hello:'%Andreas%'});
it has to return first data. Below a real sample from my project.
var mongo = require('mongodb');
var Server = mongo.Server;
var Db = mongo.Db;
var server = new Server('ds053479.mongolab.com', 53479, {auto_reconnect : true});
var db = new Db('orient', server);
db.open(function(err, client) {
client.authenticate('testname', 'fsfsff', function(err, success) {
var collection = db.collection('Models');
collection.insert({Name:'test1'});
// Fetch the document
collection.findOne({Name:'%world_no_safe%'});
});
According to the MongoDB Manual you can use the $regex operator:
collection.findOne({Name: { $regex: '.*world_no_safe.*' }});

adding a query string to an URL

I'm working on a app in Node/Express/Jade environment.
Let's assume I start my app, and direct my browser to this URL:
/superadmin/?year=2012
On this page, i find a list with object, sorted in a default order. Here is also a link that will re-sort the list objects in another order. I jade this link look like:
a(href = '?sortAfter=company&ascending=1') Company
If i press this link, I will get the items sorted in the way I want, but the ?year=2012 from earlier query string will be lost.
Question: How do I re-write this link to add the new query strings, and not replace it.
Got the same problem, here's how I fixed it:
Installed https://npmjs.org/package/URIjs via npm install URIjs
Now, in your route :
var URI = require('URIjs');
app.get('/', function(req, res) {;
res.render('views/index.jade', {
urlHelper: function (key, value) {
return (new URI(req.url)).setQuery(key, value);
}
});
};
And in jade :
a(href=linkHelper('acesnding',1)) Company
I've come up with my own npm package for just this cause -> https://www.npmjs.com/package/qsm
Example:
var qsm = require('qsm');
app.get('/', (req, res) => {
res.render('views/index.jade', {
addQueryString: (key, value) => {
return qsm.add(window.location.href, [{ query: key, value }]);
}
});
});
and in jade
a(href= addQueryString('acesnding',1)) Company
Please refer the README in qsm and you'll see how easy it is to append querystring, remove specific querystrings and even parse and much more!
You can even clear, remove and replace querystrings. The best of all, it doesn't have to be a URL, it can be whatever string you can think of, but it will behave as that string is an url and append querystring to it: e.g: ?key=value or &key=value depending on what is already present.

node + express + mongoose query authentification

Im building a simple web app app in express, and I'm a bit stuck in the authentification for my sessions, im going to validate everything in the client with backbone and regExp eventually when i start building the front end of the app. no basycally i have an issue with the query in mongoose returning a mongoose document object. I've looked up a couple of solutions, in the query you can use a .lean() to get an object, or grab the return from the query and apply a .toObject(), that all works fine and dandy, however when i try and authenticate the value of the key with a string it returns false. i'll post an example code, its not exactly what i've got, but its close enough to get the point across.
this would be an example of my models file
var User = new Schema({}, { strict: false });
User.method('authenticate', function(plainText) {
var object = this.toObject();
return plainText == object.password; });
mongoose.model('User', User);
mongoose.connect( definitions.dbConnect );
and in my app file i would have something like
app.get('/session', routes.showLogin);
app.post('/session/new', routes.login);
and in my routes file id have something like
exports.login = function(req, res){
var userQuery = new RegExp(req.body.username , 'i');
var passwordQuery = new RegExp(req.body.password, 'i');
var Query = User.find();
Query.findOne().where('username', userQuery).exec(function(err, user){
if(user && user.authenticate((req.body.password))){
req.session.userId = user._id;
}else{
res.redirect('/session');
}
});
},
Any ideas would be appreciated, its probably very silly... : /
Thanks in advanced!
YEah robert klep was right on the money, After i seearched the mongoose Documentation and the mongodb docs as well, it became clear that queries return a mongo document object, in terms should be converted to the same object or variable types for opperands to work.

Categories