Passing Data between app.post to app.get in nodejs - node.js

I am fairly new to nodejs and express. I am using nodejs and handlebars to create a simple back end CRUD App. Right now I am stuck on how to pass the value from a form I created in handlebars to an app.get function in my index.js file so inside my app.get function I can use the value to do a database query. After I do the query I want to display the results using app.get and render it to web page.
This is my Handlebars code:
<section id="main" class="wrapper">
<div id="view" class="container">
<section id="main" class="wrapper">
<div id="class" class="container">
<div class="card-body">
<form action="/getid/submit" method="POST">
<div class="form-group">
<label for="id"></label>
<input type="text" class="form-control" id="id" name="id"
placeholder="Enter ID">
</div>
<button type="submit" class="btn btn-primary">Enter ID</button>
</form>
</div>
</div>
</section>
This is the post function in index.js
app.post('/getid/submit',(req,res)=>{
const id = req.body.id;
console.log(id);
res.redirect('page1');
});
This is the app.get function:
app.get('/view/id',(req,res)=>{
//id = ?
var sql = `SELECT * FROM class WHERE Id =${id}`;
db.query(sql,function (err,result){
if(err) throw error;
res.render('page2',{title: 'test', items: rows})
});
});
My main question would be How do I pass the value that I am getting from the app.post form to my app.get function so I can run the query with that ID and render the values to the webpage. THank you in advance.

The id you need to achieve is in request parameters. So you should try:
app.get('/view/:id', (req, res) => {
//id = ?
const id = req.params.id
var sql = `SELECT * FROM class WHERE Id =${id}`;
db.query(sql, function (err, result) {
if (err) throw error;
res.render('page2', { title: 'test', items: rows })
});
});

Related

how to use one ejs template for updating and showing info from mongoose/mongodb?

this is my app.js file for showing and updating info for my posts in one single Ejs template called compose: when I run my code I get this error
**
SyntaxError: missing ) after argument list in C:\Users\john\Desktop\blog\views\compose.ejs while compiling ejs**
app.post("/compose", function (req, res) {
var title= req.body.postTitle
var content= req.body.postText
const post = new Post({
title: title,
content: content
});
post.save(function(err){
if (!err){
res.redirect("/");
}
});
// res.redirect("/");
});
// update posts
app.get('/update/:postid', function (req, res) {
const updateId = req.params.postid;
Post.findById({_id: updateId}, function (err, record) {
if(!err) {
if(window.location.href.indexOf(''))
res.render('compose', {post:record});
}
});
});
and this is my compose Ejs file that I wanna do both showing and updating info with Mongodb in Ejs template:
<h1>Compose</h1>
<form action="/compose" method="post">
<div class="form-group">
<label for="posttitle"> Title</label>
<input type="text" id="" class="form-control" name="postTitle" placeholder="Title" value="<% if(window.location.href.contains("update/") > -1) { %> <%= post.title } %>" >
</div>
<div class="form-group">
<label for="desc">Description</label>
<textarea class="form-control" name="postText" id="desc" cols="30" rows="10" placeholder="Description">
<% if(window.location.href.contains("update/") > -1) { %>
<%= post.content } %>
</textarea>
</div>
<button class="btn btn-myPrimary" type="submit" value="" name="button">Publish</button>
</form>
I tried to show info from mongodb it was okay so then i made a route for updating the info using same template it gives me error

Express function sending multiple times

My react js file is currently like this
export default function Blog() {
const [title, setTitle] = useState('');
const [blog, setBlog] = useState('');
const sumbitBlog = () => {
axios.post('http://localhost:3001/api/insert', {
title: title,
blog: blog
});
}
return (
<div className='container'>
<div className='row'>
<form className='col-lg-12 form-group'>
<div className="form-group">
<label for="formGroupExampleInput">Title</label>
<input type="text" className="form-control"placeholder="Title" name="title" onChange={(e)=>{
setTitle(e);
}}/>
</div>
<div className="form-group">
<label for="formGroupExampleInput2">Body</label>
<input type="text" className="form-control" placeholder="Body" name="blog" onChange={(e) =>{
setBlog(e);
}}/>
</div>
<button className='btn-primary' type="submit"onClick={sumbitBlog()}>Submit</button>
</form>
</div>
</div>
);
}
And my nodejs back end code :
app.post('/api/insert', (req, res) =>{
const title = req.body.title;
const blog = req.body.blog;
const sql = `INSERT INTO posts (title, body) VALUES ("this","works")`;
db.query(sql,[title, blog], (err, result)=>{
if(err) throw err;
console.log(title);
console.log(blog)
});
});
even though it looks right, it keep sending multiple requests
I have I don't know what is happening, I tried using different ways of doing it looking from the internet, but only this way it inserts to the database. any other way it wont even try connecting to it.
the database
Try to pass a reference to the function instead of firing it every time you render it.
So:
onClick={sumbitBlog}
instead of:
onClick={sumbitBlog()}
Your backend function does not send a response back to the client, because it lacks a res.json() function call or similar. If you insert a statement
res.json(result);
after the two console.log statements, the client will receive a JSON response, which you must then use to somehow update the client so that the user can read that the insertion was successful. The following code simply alerts the user and displays the JSON, but you probably want something more elegant.
const sumbitBlog = async () => {
var response = await axios.post('http://localhost:3001/api/insert', {
title: title,
blog: blog
});
alert(JSON.stringify(response.data));
}

Getting specific record using user input in form with MongoDB, NodeJS and Angular5

I am trying to get back a record out of my MongoDB database using user input on an Angular template. Here's what's in my api.js file:
// Response handling
let response = {
status: 200,
key: [],
message: null
};
router.get('/keys/:key', (req, res, next) => {
connection((db) => {
db.collection('keys')
.findOne({key: req.params.key})
.then((keys) => {
response.key = keys;
res.json(keys);
})
.catch(err => {
return next({ status: 500, message: 'messed up'})
});
});
});
Here's my keys.service.ts file:
#Injectable()
export class KeysService {
result: any
constructor(private _http: Http) {}
getKeys(typeKey) {
return this._http.get(`/api/keys/:key${typeKey}`)
.map(result => this.result = result.json().key);
}
}
Here's the template (I apologize about the formatting):
<div class="container">
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
</div>
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<input type="text" [(ngModel)]="typeKey">
<button class="btn btn-primary" (click)="getKeyClass(typeKey)">Check Your
Key Spelling</button>
<br><br>
<h2>The Correct Key Spelling is: {{ keySpelling }}</h2>
</div>
</div>
</div>
What I am receiving as an error right now is "type error, can not read property key of null". It is referring to "key" in the keys.service.ts file on the last line.
I am not using mongoose or monk here. I had this working with a general query of my db that gave me the entire contents of the collection "keys" but when I try and make an individual query, no dice. Anyone have any ideas what I am doing wrong?

POST form route has POST route in address bar

I am using node + express. I currently have a text input in a form where when you submit it searches for users in a mongo DB with the given search term. However, whenever I perform a search, the URL changes to "localhost:8080/searchGlobalUsers" when it should be "localhost:8080/talk". Here is my post route:
app.post('/searchGlobalUsers', function(req, res){
var regex = new RegExp(req.body.globalUserSearch, 'i');
console.log("GLOBAL_USER_SEARCH: " + req.body.globalUserSearch);
User.find({username: regex}, function(err, globalUserSearchQuery){
res.render("talk", {globalUserSearchQuery : globalUserSearchQuery});
});
});
And here is my text input + form
<form action="/searchGlobalUsers" method="POST" >
<div class="row">
<input type="text" name="globalUserSearch" class="u-full-width" placeholder="Search" id="add-friend-search-input">
</div>
<div class="row">
<button class="button-green-large" class="u-full-width" id="add-friend-search-submit">Search</button>
</div>
</form>
render function is use to provide view to the client
just use this code
app.post('/searchGlobalUsers', function(req, res){
var regex = new RegExp(req.body.globalUserSearch, 'i');
console.log("GLOBAL_USER_SEARCH: " + req.body.globalUserSearch);
User.find({username: regex}, function(err, globalUserSearchQuery){
req.flash('info', globalUserSearchQuery);
return res.redirect("/talk");
});
});
app.get('/talk', function(req, res){
res.render("talk", {"globalUserSearchQuery" : req.flash('info')});
})

save answer with button radio using MEAN stack with MVC framework

i am setting a form with Mean Stack,
in form.html i have
<div ng-controller="InfoCtrl">
<form method="post" ng-submit="info()" name="infoForm">
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="Homme" value="Homme" checked>
Homme
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="Femme" value="Femme">
Femme
and in the controller info.js i have :
angular.module('MyApp')
.controller('InfoCtrl',[ '$scope', 'infor', function($scope, infor) {
$scope.info = function() {
infor.info({
age: $scope.age,
sexe: $scope.optionsRadios
});
};
}]);
another file infor.js, it only contains the error message after the set of the form, in the class server.js i have this function:
app.post('/infor/info', function(req, res, next) {
console.log('ok');
var query = {'email' : 'mail#mail.fr' };
var age1 = req.body.age;
console.log(req.body.optionsRadios);
User.findOneAndUpdate(query,{ age: age1 } , {upsert:true},function(err, doc){
if (err) return res.send(500, { error: err });
return res.send("succesfully saved");
});
});
but i didn't knew how to save the answer of the button radio in the query like i did in the set of new text. I have searched in many forms but it i didn't found an answer!

Resources