POST form route has POST route in address bar - node.js

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')});
})

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

Page needs to be refreshed to load the data from an API in Node

So I'm building a simple web app that gets data from an API that needs to be displayed on the screen.
However after the Post request is made, the data from the API gets logged through the console.log() however it does not get displayed on the screen though I've got the correct code, it gets displayed after a manual refresh.
I'm using EJS to display the API data on the screen.
The app.js has the following:
var cityName='';
var temperature='';
var pressure='';
app.get('/',function(req,res){
res.render('home');
});
app.get('/results',function(req,res){
res.render('results',{
cityName: cityName,
pressure:pressure,
temperature:temperature,
}
);
});
app.post('/',function(req,res){
cityName=req.body.cityName;
const api_url= 'https://api.openweathermap.org/data/2.5/weather?q='+ cityName +'&appid=8bb235e1990db4b5ae16f92e920bad25';
https.get(api_url,function(output){
//console.log(output);
output.on('data', function(data){
const weatherData= JSON.parse(data);
// WEATHER
temperature=Number(weatherData.main.temp)-273.15;
pressure= Number(weatherData.main.pressure);
console.log('Temparature:'+temperature+' °C');
console.log('Pressure:'+pressure + ' hPa');
});
});
res.redirect('/results');
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function(){
console.log("Server ativated at port successfully");
});
The results.ejs file simply has the following:
<div class="container">
<div class="card-deck">
<div class="card bg-light mb-3" >
<div class="card-header">City</div>
<div class="card-body">
<ul>
<li><p class="card-text" name="cityName">City Name: <%= cityName %>.</p></li>
<li><p class="card-text" name="temperature">Temperature: <%= temperature %> °C.</p></li>
<li><p class="card-text" name="pressure">Pressure: <%= pressure %> hPa.</p></li>
</ul>
</div>
</div>
</div>
</div>
The home.ejs file has:
<div class="container1 container">
<form method="post" action="/">
<div class="brand-logo"></div>
<div class="brand-title">WEATHER MONITORING</div>
<div class="inputs">
<label>CITY NAME</label>
<input autocomplete="off" name="cityName" type="text" placeholder="Mumbai" />
<button type="submit">CHECK</button>
</form>
</div>
You redirect the user before the data loads
Move your redirect inside the callback
app.post("/", function (req, res) {
cityName = req.body.cityName;
const api_url =
"https://api.openweathermap.org/data/2.5/weather?q=" +
cityName +
"&appid=8bb235e1990db4b5ae16f92e920bad25";
https.get(api_url, function (output) {
//console.log(output);
output.on("data", function (data) {
const weatherData = JSON.parse(data);
// WEATHER
temperature = Number(weatherData.main.temp) - 273.15;
pressure = Number(weatherData.main.pressure);
console.log("Temparature:" + temperature + " °C");
console.log("Pressure:" + pressure + " hPa");
res.redirect("/results");
});
});
});

Passing Data between app.post to app.get in nodejs

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 })
});
});

React reloads the page after replacing images

I am uploading images to a server. If it is present and replaced, then React refreshes the page with a loss of state. How can I stop this behavior?
Node:
let form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
let {size, path, name, type} = files.image,
newpath = pathLib.join(__dirname, '../client/public/uploads') + name;
fs.rename(path, newpath, function (err) {
if(err) throw err;
});
});
React:
<form id="uploadForm">
<input id="uploadInput" name="image" type="file" />
</form>
<span onClick={() => {
let form = document.querySelector("#uploadForm"),
formData = new FormData(form);
if(form.querySelector("#uploadInput").files.length)
uploadFiles(formData, (res) => {
console.log(res.data.errors);
});
}}>Save</span>
An important addition! Page refreshed even without interaction with React components. Replacing an image through the Windows file manager calls the re-render.
Just call event.preventDefault() when submit form. See the example here:
<form id="formSubmit"}>
<input id="uploadInput" name="image" type="file" />
<button type="submit"></button>
</form>
document.getElementById('formSubmit').addEventListener('submit',function(event){
event.preventDefault()
// write here your others code
})

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