Express get URL and delete certain object - javascript

Now I'm developing CRUD(Create, Read, Update, Delete) App with Express and LowDB.
And I successfully developed the create and read but Delete Function is not working.
There are detail page like this
as you can see there are trash can Icon and actually I also have some problem the submit button but It's not important so I just make submit button.
this is the part of the pug file
aside#Delete.is-visible
form(method="post" action='/delete_process')
input(type='submit')
a#DeleteButton(role='button')
img(src='https://png.icons8.com/ios/35/000000/waste-filled.png' id="go_up")
span.text
| Delete
br
b this
detail page have URL (ex: DIR1WTqr2) and it's DB id
and delete Process code is like this.
/* Delete Process */
router.post('/delete_process', function (req, res) {
// GET Delete ID from URL
let id=req.params.id;
console.log(id);
db.get('project').find({
id: id
}).remove().write();
});
I thought I can get URL and find the data with the id in json file. but It's not working. When I tried to console the req.params.id it said undefined
And I think there are collision with view Detail page because Detail page code is like this.
/* GET Detail View Page */
router.get('/:id', (req, res, next) => {
// GET URL params and put it into :id
let id = req.params.id;
// console.log(id);
// GET data id to use Object
let data = db.get('project').find({
id: id
}).value();
// Get github URL
let url = data.githuburl;
// Use Request Module to parsing Web page
request(url, function (error, response, html) {
if (error) {
throw error
};
// Parsing readme ID in github page
var $ = cheerio.load(html);
$('#readme').each(function () {
// save to readme Variable
let readme = $(this).html();
// console.log(data);
// console.log(id);
res.render('detail', {
dataarray: data,
name: data.name,
url: data.url,
explanation: data.explanation,
imgurl: data.imgurl,
markdown: readme,
startDate: data.pjdate1,
endDate: data.pjdate2,
githuburl: data.githuburl,
sumlang: data.sumlang
});
});
});
});
because of :id when I click the /delete_process it goes to detail page I think.

Pug is very specific about your indentation. Your button wasn't contained inside the form - it was a sibling. Make sure that you've always got two spaces when you want an element to be contained inside another.
Change the pug template to this and the button will submit properly:
aside#Delete.is-visible
form(method="post" action='/delete_process')
input(type='submit')
a#DeleteButton(role='button')
img(src='https://png.icons8.com/ios/35/000000/waste-filled.png' id="go_up")
span.text
| Delete
br
b this
But wait there's more! You aren't passing the id of the restaurant back with the form.
I can't see how you're using the restaurant id in the pug, but you'll need to add that into the form somehow too. Let's assume it's a variable in the pug template called restaurant.id.
Your node.js route handler is trying to read req.params.id which means that it's going to look to the url to get the id of the restaurant. You can add the id to the request like this:
aside#Delete.is-visible
form(method="post" action='/delete_process/' + restaurant.id)
input(type='submit')
Then, you'll also need to modify your route to include the id parameter:
router.post('/delete_process/:id', function (req, res) {
A different way to do this would be to add a hidden form field that sends the id with the form (here's an article that explains this concept). If you do it this way you can change the form to look like this:
aside#Delete.is-visible
form(method="post" action='/delete_process/' + restaurant.id)
input(type='hidden' name='id' value= restaurant.id)
input(type='submit')
Then your delete handling route can pick it up like this:
router.post('/delete_process', function (req, res) {
// GET Delete ID from form field
let id= req.body.id;
The first method of passing the id (in the url) is standard for ajax requests, the second method (as a field in the form) is the standard for posting a form.

Related

how to make a button call a find() functtion in server.js > mongdb and show it in html?

I'm creating this web app using node express and mongodb atlas.
app.get('/', (req, res) =>{
User.find({firstName: 'vinicius', (err, users) =>{
res.render('index', {
userList: users
})
})
})
with this piece of code I can retrieve the data with first name 'vinicius' and show it on the html with the following:
<%userList.forEach(users =>{%><p><%= user.firstName %></p><%})%>
my challenge is: i want to create a buton on html to call this query
in fact i would like to have an input field where i can put the cpf number (it's like the social security number), that is, i write the CPF and then query it and it returns on the page
and another button where i can query all information and show it on brower (i can do the rule of all, it would be writtn in the user find().
just dont know how to call it from the browser
You can create a button with a click listener like this:
<button id="someid" onclick="myFunction()">Click me to fetch user</h3>
Then, inside you script, you should have a function called myFunction that is called when the button is pressed.
<script>
function myFunction() {
// Here you can grab your input field by id, and pass its value to your API
// Do you API call and populate data on the frontend
}
</script>
Here's how you can use the fetch API to do your API call:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Here's how you can grab and mutate HTML elements:
https://www.w3schools.com/jsref/met_document_getelementbyid.asp

How to get only one user instead of a list?

I try to get from a list of users to only one user and display his profile on another page.
I want to do so with the routerLink and passing on an id of this specific user to the next page.
The routing is working, Im directed to the profile page but when I log the results of the http request I still get back the whole list of users like in the users page instead of the details of one user.
I have tried many things like changing the path of the url in my user.service.ts but that didn't solve the problem I even got 404 request errors when using this path ${this.url}/users/${id}/ instead of ${this.url}/users/?i=${id}/ (where its working).
The api docs is saying though that in order to retrieve one single user its http://1234//users/{id}/ it this scheme while id is an integer. But when I want to apply that scheme I get the 404 error.
Thats why I have to use the ?I= version but there the problem is I only get the full list of users on the next page.
MY CODE:
user.service.ts
// get a user's profile
getUserDetails(id): Observable<any> {
return this.http.get(`${this.url}/users/?i=${id}/`); // why add ?i
}
user.page.ts
// get all users in the users page
getAllUsers() {
this.userList = this.userService.getList()
.pipe(map(response => response.results));
}
user.page.html
<ion-avatar class="user-image" slot="start" [routerLink]="['/','profile', 'user.id']">
<ion-img src="assets/22.jpeg"> </ion-img>
</ion-avatar>
profile.page.ts
information = null;
...
ngOnInit() {
// Get the ID that was passed with the URL
let id = this.activatedRoute.snapshot.paramMap.get('id');
// Get the information from the API
this.userService.getUserDetails(id).subscribe(result => {
this.information = result;
console.log(result);
});
}
It seems like the url is wrong. If it was me I would console.log the url and compare it to the docs. Heres a snippet to try a few variations:
const id = 1;
const options = [
`${this.url}/users/?i=${id}/`,
`${this.url}/users/?i=${id}`,
`${this.url}/users/i/${id}/`,
`${this.url}/users/i/${id}`,
`${this.url}/user/?i=${id}/`,
`${this.url}/user/?i=${id}`,
`${this.url}/user/i/${id}/`,
`${this.url}/user/i/${id}`,
];
for (const option of options) {
try {
const response = await this.http.get(option);
console.log(options, response);
} catch (e) {
}
}
I would also consider dropping the second http request. If the first request returns all the required data you could just store it in a variable on the service.

Url issues in nodejs search and pagination

I have a results page with pagination. Routes are as follows:
app.get("/results",function(req,res){
query= select * from courses where
// the following line adds search parameters from req.query to the sql query//
Object.keys(req.query.search).forEach(function(key){
query+= key + " = "+ (req.query.search[key])
})
conn.query(query,callback(){
....
....
...
res.render("results",{results,results})
})
)}
This code works fine at first but as soon as I click pagination buttons to move to second page , the search_query parameters do not pass to second page and req.query.search becomes undefined there for sending undefined results error.
Anyone?
It seems that your method does not send the search_query parameter but you can try this so you do not have problems with undefined.
app.get("/results/:id", function (req, res) {
const { id } = req.params;
// Now in this part you can use the value of the variable id for your query
// Implementing my amazing query...
});
¿What is the difference?
Using this form we ensure we have a value that we can use for the page, so now our requests will be for example http://localhost/results/14 where 14 can be my id that I use as a filter in the query.

How to create a variable in jade to be used in node.js

I am new to express node and I am responsible for the front end of a web app. I need to be able to have the user press a link and for that link to when press pass variable to index.js this link lets the user choose what category of question that they want to be tested on. I do not think that having a different route for each category is the best option. but because I am new I am not sure what to do.
Here is the code for my link in jade (I want to add something here to do what I want) there is a link to a screenshot of the page at the bottom of this post.
li.active
a(href='freeplay')
i.fa.fa-edit
span.nav-label Freeplay
span.fa.arrow
ul.nav.nav-second-level
li
a(href='freeplay/category') Category1
li
a(href='freeplay/category') Category2
li
a(href='freeplay/category') Category3
li
a(href='freeplay/category') Category4
li
a(href='freeplay/category') Category5
and Here is my index.js that handles it. temp is the variable that I want to hold the string of the category.
//Handle the free play request
router.get('/freeplay' , isAuthenticated, freeplay.startFreePlay);
//Handle the free play request with category
router.get('/freeplay/category' , isAuthenticated, freeplay.startCategoryPlay);
and finally the node.js that I want to be able to read a variable in to temp is the variable I want to assign the user chosen category to.
exports.startFreePlay = function(req, res) {
//grab a question that the user has not gotten right
//Get the users logged in id
userId = req.session.passport.user;
freePlayLogic.getQuestion(userId, function(question){
res.render("FreePlayQuestion", { question: question , questionID : question._id.toString()});
})
//Pass the question to render
};
exports.startCategoryPlay = function(req, res){
//grab a question that the user has not gotten right
//Get the users logged in id
userId = req.session.passport.user;
/**
* get a question from category "temp"
*/
freePlayLogic.getQuestionFromCategory(userId, "temp", function(question){
res.render("FreePlayQuestion", { question: question , questionID : question._id.toString()});
})
}
Thanks in advance for help!
here is a screenshot of the web app with the category choices
so what it looks like you are trying to do is have a button send data back to your server. Doing this requires making another request to the server. You can add a route which will process this data like so...
app.get('/question/:id', function(req, res) {
var id = req.params.id;
//do something with this id like render a page
);
And then your links would look something like this
a(href="/question/1") Question 1
a(href="/question/2") Question 2
This should work, if you have any questions just leave a comment :)
Try adding this test route
app.get('/test/id', function(req, res) {
res.send(req.params.id);
);

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