How to make a function of arrays in node js, handlebars - node.js

I was new to node.js and trying to render a list of fruits using hbs or handlebars in the client that came from the server
I wonder how to make a functions or event in every fruits
This is how i render the fruits
app.js
app.post('/getList', function(request, response) {
if (request.session.loggedin) {
//here i am sending the arrays to the client in the homepage
response.render('home',{fruits:fruits()});
} else {
response.send('Please login to view this page!');
}
This is my home.bhs
<form action="getList" method="POST">
<input type="text" name="username" placeholder="Username" >
<input type="password" name="password" placeholder="Password" >
<input type="submit" value="Insert">
<ul>{{#each fruits}}</ul>
<li>{{this}}</li>//Here are the list of frutis and i want to make them clickable
{{/each}}
</form>
});
This is my arrays
let fruits=()=>{
let list = ["apple","asdas","bbb","ccc","dddd"];
return list;
};

Related

POST data from multiple forms in single request using Node.js

I'm trying to send a POST request to an API from multiple forms at once. Essentially I have a site where users will input data to multiple locations before clicking a button to run a calculation. Clicking the button will ideally send a POST request to the API containing all the information the user has input from various places.
Within the body of index.html I've tried the following, effectively trying to get both forms to POST to the same address, but only including a submit button with one.
<form action="/" method="post" name="myForm">
<div>
Here is some text at the top of the form...
</div>
<input type="text" name="num1" class="inp1" placeholder="First Number">
<input type="text" name="num2" class="inp2" placeholder="Second Number">
<button type="submit" name="submit">
calculator
</button>
</form>
<form action="/" method="post" name="myForm">
<div>
Here is a 2nd form
</div>
<input type="text" name="num1" class="inp1" placeholder="Third Number">
<input type="text" name="num2" class="inp2" placeholder="Fourth Number">
</form>
My Node.js code to spin up a server and look at the POST request:
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.urlencoded({
extended: true,
})
);
const tempResult = fs.readFileSync(
`${__dirname}/templates/overview.html`,
"utf-8"
);
app.get("/", (req, res) => {
res.send(tempResult);
});
app.post("/", (req, res) => {
console.log(req.body);
res.send(tempResult);
});
const port = 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
In the console this simply returns:
{
num1: val1,
num2: val2,
submit: ''
}
Where val1 and val2 are the inputs to index.html for the first form only. What am I missing here? How can I get the values from both forms in one call?
As alluded to by #Ipizzinidev the solution here lies in putting the form right at the top of the body.
<body>
<form action="/" method="POST">
<div>
Here is some text at the top of the form...
</div>
<input type="text" name="num1" class="inp1" placeholder="First Number">
<input type="text" name="num2" class="inp2" placeholder="Second Number">
<input type="text" name="num3" class="inp3" placeholder="Third Number">
<input type="text" name="num4" class="inp4" placeholder="Fourth Number">
<button type="submit" name="submit">
calculator
</button>
</form>
</body>
Inside this form you can do the usual HTML stuff and then after hitting submit it will return the following:
{
num1: val1,
num2: val2,
num3: val3,
num4: val4,
submit: ''
}
It always seems so simple in hindsight!

Post request from ejs view is not working

I'm trying to register a user to my database but I can't even make my post request work. The get part router is working but it seems post is not working.
In the app I declared routers like this(server.js file):
const userRoutes = require("./routes/user.js")
app.use('/user',userRoutes)
In the routes/user.js file:
//User register
const userController = require('../controllers/user_controller')
router.get("/register",userController.register_page)
router.post("/register",userController.register_post)
And this is the controller part (controllers/user_controller.js):
//Register get
exports.register_page = (req,res)=>{
return res.render('user/register',{layout:false})
}
//Register post
exports.register_post = async (req,res)=>{
//bla bla
}
I can see the pages but when I submit in the ejs page nothing happens. This is the view page(views/user/register.ejs):
<form id="register" method="post" action="/user/register">
<label><b>Email
</b>
</label>
<input type="text" name="email" id="email" placeholder="Email">
<br><br>
<label><b>Password
</b>
</label>
<input type="Password" name="password" id="password" placeholder="Password">
<br><br>
<label><b>Confirm Password
</b>
</label>
<input type="Password" name="confirm" id="confirm" placeholder="Password Repeat">
<br><br>
<input type="button" name="submit" id="submit" value="Register">
</form>
Your form does not send the post request, because the submit button does not have the type of submit. Change from type="button" to type="submit".

Calling a PUT to express from EJS

I am trying to call a restful api created in expressjs from EJS form.
I tried looking on google and stackoverflow, and trying lots of different methods.
orders.ejs:
<ul class="orders">
<% for(var i=0; i<orders.length; i++) {%>
<ul class="order">
<p> coffee_id <span><%= orders[i].name %></span>
amount: <span><%= orders[i].amount %></span>
quantity <span><%= orders[i].quantity %></span> </p>
</ul>
<% } %>
</ul>
<div>
<form action="/orders" method="POST" action="orders/?_method=PUT">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="coffee name" name="name">
<input type="number" placeholder="amount" name="amount">
<input type="number" placeholder="quantity" name="quantity">
<button type="submit" id="order" >Submit</button>
</form>
</div>
nodejs.app.js:
app.post('/orders', (req, res) => { // falta o EJS
db.collection('orders').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log(req.body);
res.render('orders.ejs', {
put: true
});
})
})
app.put('/orders/:coffeeid/:quantity', function(req, res) { ...
}
This code works fine individually calling them from Postman with the right parameters, but I need to call them both when I submit the EJS form.
app.get('/orders/:coffeeid',function(req, res) {
db.collection('orders').find({_id:req.params.coffeeid}).toArray, function(error,result){
if(!error && result && quantity){
return res.render('orders.ejs',{orders: result, coffeeid:result.coffeeid, quantity:'7'}); // <-- pass coffeeid to view
}
}
});
I need to read quantity also from the form and check for stock in the PUT, so for now I fixed it at '7'units, but now Cannot GET /orders
route for get orders :
app.get('/orders',function(req, res) {
// fetch all orders and display it to view
});
route for display edit page of order by coffeeid :
app.get('/orders/:coffeeid',function(req, res) {
var coffeeid= req.params.coffeeid;
db.collection('orders').find({_id:coffeeid}).toArray,function(error,result){
if(!error && result){
return res.render('orders.ejs',{orders:result,coffeeid:result.coffeeid, quantity:'7'});
}
});
});
form :
<form action="/orders/<%=coffeeid%>" method="POST">
<input name="_method" type="hidden" value="PUT">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="coffee name" name="name">
<input type="number" placeholder="amount" name="amount" value="">
<input type="number" placeholder="quantity" name="quantity" value="<%=quantity%>">
<button type="submit" id="order" >Submit</button>
</form>
to update information route will be :
app.put('/orders/:coffeeid', function(req, res) {
var coffeeid= req.params.coffeeid;
var quantity= req.body.quantity;
// save to database
}

Form: Keep posted parameters with Sails JS

I have file views/user/index.ejs
<form action="" method="POST>
<label>Username: </label>
<input type="text" class="form-control" value="<%= req.param('username') %>" name="username">
<input type="Submit" value="Submit">
</form>
Content of api/controllers/UserController.js
module.exports = {
index: function (req, res) {
sails.log(req.param('username'));
// Result: invest
}
}
Although the log print "invest", but the content of input is "undefined". I think that the array of requested parameters had not been kept.
Can anyone help me solve it? I will donate 2 eggs ;)
You can use this to pass variables to your view:
module.exports = {
index: function (req, res) {
return res.view("user/index", {username: req.param('username')});
}
}
In your view:
<input type="text" class="form-control" value="<%= username %>" name="username">

Can't update user model in express?

I'm trying to do a put request to update a user model but instead my router just sends another get request.
Here's my router
router.get('/update', isLoggedIn, function(req, res) {
res.render('update.ejs', {
user : req.user // get the user out of session and pass to template
});
});
router.put('/update', function(req, res) {
var username = req.body.username;
var profile_type = req.body.prof_type;
var pic = req.body.profile_pic;
var aboutme = req.body.whoami;
console.log(req.body.whoami);
User.findById(req.params.id,function(err, userup){
if (!userup)
return next(new Error("Couldn't load user"));
else {
userup.username = username;
userup.prof_type = profile_type;
userup.profile_pic = pic;
userup.whoami = aboutme;
userup.save(function(err) {
if (err)
console.log('error on update');
else
console.log('successful update');
});
}
});
res.redirect('/profile');
});
Here's my html input form
<form action="/update" method="put">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username">
</div>
<div class="form-group">
<h2> Pick a type of profile</h2>
<input type="radio" class="form-control" name="prof_type" value="true">Tutor<br>
<input type="radio" class="form-control" name="prof_type" value="false">Student
</div>
<div class="form-group">
<label>Link to profile picture</label>
<input type="text" class="form-control" name="profilepic">
</div>
<div class="form-group">
<label>About me</label>
<textarea name="whoami" class="form-control">Enter text here </textarea>
</div>
<button type="submit" class="btn btn-warning btn-lg">Update</button>
</form>
I've also tried changing them to be /update/:username, however, after I click the update button with the fields, I GET this address
http://localhost:3000/update?username=bob&prof_type=false&profilepic=bob&whoami=bob
Not sure why I'm not updating the model or even why it's not putting. Any help is much appreciated, thanks!
HTML only supports GET and POST requests. See the specification for details:
The method and formmethod content attributes are enumerated attributes
with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET
method. The keyword post, mapping to the state POST, indicating the
HTTP POST method. The invalid value default for these attributes is
the GET state. The missing value default for the method attribute is
also the GET state. (There is no missing value default for the
formmethod attribute.)
You can use the PUT method only with an ajax request. For example in jQuery:
$.ajax({
url: '/update',
type: 'PUT',
success: function(result) {
// Do something with the result
}
});

Resources