Express routing to search results - javascript

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.

Related

How can I extract and query data from MongoDB using input from Javascript webpage

I am working on a webpage which takes in input and depending on the user's inputted area code, my program will return data corresponding to this. My database is stored currently using MongoDB and I have attempted to query data using the find function and by connecting to my cluster. Below is the example of a section I have tried (with username and password hideen): Please let me know if anyone can find a solution to this, or if i am connecting this wrong. I am just a student so would appreciate any input.
Thank you!!
This is what i have currently tried, I intially tried to code in Python but this also did not work.
const uri = "mongodb+srv://<username>:<password>#cluster0.mongodb.net/data-police?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("set-1");
// perform actions on the collection object
collection.find({}).toArray(function(err, result) {
console.log(result);
client.close();
});
});

Cannot GET / error when trying to create a new page for a user's post

Trying to render a new page using ejs.
I don't have a big experience with js. Managed good progress so far but at this point I'm stuck.
Currently building a blog, and so far can render the about, or contact pages easily.
When a new user adds a new post, I'm trying to render a new page for that post at localhost:3000/post/test (test is the name of the post).
I receive : Cannot GET /post/title.
If with the same code I only try to check the equality between const storedTitle and const requestedTitle, and if true, console.log("match found") that works just fine.
When using the code below, it doesin't work anymore.
Below is the code I've written for that, but probably in order for one to help me out here, he/she would need to see more than that.
This is my first post on here, sorry if in any case, it does not comply with the community policy.
Thanks for the help!
app.get("/posts/:nameOfPost", function(req, res) {
const requestedTitle = _.lowerCase(req.params.nameOfPost);
posts.forEach(function(post) {
const storedTitle = _.lowerCase(post.titleInput);
if (storedTitle === requestedTitle) {
res.render("post", {
title:post.title ,
content:post.content
});
};
});

Most browsers do not 'remember' the result of Ajax request when going back to page

I have a page with a form that gives a user the option to filter a list of objects (programs) by selecting options. For example, they could select the option architecture to show only the programs which contain that subject. An AJAX-request is sent to the server, which then returns the results. So far, everything works.
My problem: in some browser when someone clicks to go to another page and then goes back to the page where the form is, the results are reset, although the form selection(s) are still visible. In Chrome this is a problem, whereas in Firefox this does not happen. On this page you can see a live example.
My JavaScript AJAX post-request looks like this:
let sendQuery = () => {
let programsList = document.getElementById('programs-list');
axios.post('/programs/getByFilter', filter )
.then(function (response) {
programsList.innerHTML = response.data;
})
.catch(function (error) {
console.log(error);
});
}
And then in PHP (I use Symfony):
/**
* #Route("/getByFilter", name="program_get_by_filter")
*/
public function returnProgramsByFilter(Request $request, SearchHelper $searchHelper)
{
$jsonFilter = $request->getContent();
$filter = json_decode($jsonFilter, true);
// the query is done here.
$programs = $searchHelper->findByFilter($filter);
return $this->render('program/programs_ajax.html.twig', [
'programs' => $programs ]);
}
Now I have looked for similar questions and found this one and this one, but I haven't been able to solve the problem. Initially I tried to send the request as a GET-request instead of a POST-request, but the data I send is JSON and I did not manage to make it work. I am not really sure if that has to do with the JSON or not. My understanding of JS is really poor. Then I tried with a session variable like so:
$jsonFilter = $request->getContent();
$filter = json_decode($jsonFilter, true);
$session->set('filter', $filter);
And then:
if($session->has('filter')){
$programs = $searchHelper->findByFilter($session->get('filter'));
} else {
$programs = $programRepository->findAll();
}
This does not really work either because the original options will be overwritten when going back and making a new selection. Also, with my JS I show the current filters that are being used and the number of results. That's gone too.
Is there a JS solution or should I try to fix this in PHP?
Update:
I have been able to set filter as a cookie every time an ajax call is made by making it a string with JSON.stringify(filter) and then I get it and use it with:
// Getting the cookie, parsing it and running the query.
var filterCookie = getCookie('filter');
if (filterCookie) {
var objectCookieFilter = JSON.parse(filterCookie);
let programsList = document.getElementById('programs-list');
axios
.post('/programs/getByFilter', objectCookieFilter )
.then(function (response) {
programsList.innerHTML = response.data;
})
.catch(function (error) {
console.log(error);
});
}
This will re-run the last query that was set in the cookie. The problem that remains though is that all the filter-badges are set on a change event of the checkboxes and I cannot figure out how to show them based on the cookie (or perhaps some other way?)

Express res.render stuck in infinite loop

Steps:
pull data from mongodb to populate a link on search page. Be able to click the link to take end user to the generic business page which is auto filled by mongodb. render the page with the JSON data from mongodb.
Issues:
res.render gets stuck in Infinite Loop (no error is thrown also)
I've tried adding an if statement so res.render would not render again, yet still stuck in a loop.
routes/business.js
router.get('/:business', (req, res) => {
console.log(req.params.business);
Business.getBusinessByUrl(req.params.business, (err, business) => {
if (err) throw err;
res.render('business', {
found: true,
business_name: business.business_name,
business_profile_image: business.business_profile_image,
business_url: business.business_url
});
});
});
module.exports = router;
models/business.js
module.exports.getBusinessByUrl = function (businessUrl, callback) {
const query = { business_url: businessUrl };
Business.find(query, callback);
};
Here is what it looks like in the browser :
Imgur
Let me know if you need any other code.
After a while of searching I couldn't find anything helpful. Eventually I figured it out. It happened to be that when I had commented out the line <div w3-include-html="file-included.html"> it stopped infinitely loading. A thank you too everyone who tried to help me.

How create a simple get form that will create a dynamic route, depending on the value of the search field (MONGODB and Node.js)

i want search throw the database for a value that the user puts in a get form.
The backend is very simple, i know how to search throw the database and render the result..
app.get('search/:id', function(req, res) {
var id = req.param("id");
mongoose.model('Something').find({
// the field that i want find. For example:
_id: id // This will search for the id field in the database, them will return a object if finds a match.
}, function(error, object){
if (error) {
res.send(error);
}
else {
res.send(object);
}
}
);
});
This script will work.
Now i'm having problems with the HTML.
I need a get form that will send a user to /search/SOMETHING THAT THE USER WANTS SEARCH, but i don't know exactly how to change the url dinamically..
Any help is very very welcome.
If you don't know how to achieve desired behaviour in the HTML, you could still do it in the backend - by setting a redirect. Your incoming request after form submission would be something like ?inputName=user search string.
You could then take the value of the query and perform an internal redirect to your route
app.get('search', function(req, res) {
res.redirect('/search/' + req.query["inputName"]);
});
to get a form to pass GET params in a nice express-like way, you need to hook on the onSubmit of the form and then trigger an XHR/ajax request instead of the form-post.
Or you can read the querystring via req.query.inputFieldName if you are okay having the url look like /search/?inputFieldName=AwesomeSearchString
I'd take the XHR/ajax way as it also prevents the page from reloading and thus improving user-experience.

Categories