Using the Express.js app.post request is not working - javascript

I am having an issue with the Express.js library.
I have been trying to set up a basic post request with the route.
I have installed and using body-parser for the post data.
If I specifically add app.post it does not work but if I use GET or app.all it works just fine with my post data.
Could some one take a look at my code and see what i could be doing wrong? Also just for a further clarification i will be splitting all this up later on i just have the data base connection and every thing else in one file to test things.
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
var getuser_Information;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/data/db/');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
//testing the mogno db for createing a new table schema for a user login using the mognose api example
var UserSchema = mongoose.Schema({
name:String
});
var usersinfo = mongoose.model('Userinformation', UserSchema);
//sets up the log in
app.post('/',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
console.log(silence);
});
res.render('def',{
firstnames:getuser_Information
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<h1>Hello, world!</h1>
<form class="navbar-form navbar-left" role="search" method="post">
<div class="form-group">
<input type="text" class="form-control" name="usernames">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<h1>Hello <%= firstnames %></h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>

So i was not routing the correct information and figured out the diffrences of when using app.all. here is the code that i have now.
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
var getuser_Information;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/data/db/');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
//testing the mogno db for createing a new table schema for a user login using the mognose api example
var UserSchema = mongoose.Schema({
name:String
});
var usersinfo = mongoose.model('Userinformation', UserSchema);
//sets up the log in
app.get('/',function(req, res) {
res.render('def',{
firstnames:""
});
});
app.post('/run',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
else
res.render('def',{
firstnames:getuser_Information
});
});
});
process.on('uncaughtException', function (err) {
console.log("\n\r *Uncaught Exception event* \n\r")
console.log(err);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<h1>Hello, world!</h1>
<form action="/run" class="navbar-form navbar-left" role="search" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="usernames">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<h1>Hello <%= firstnames %></h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>

app.post('/',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
else
res.render('def',{
firstnames:getuser_Information
});
});
});
Node.js is asynchronous.

Related

Database connection error with nodejs and xampp mysql

So ive been trying to make a login form using nodejs and xampp mysql but after entering details from the table and clicking on login button the page keeps loading and nothing happens.... i cant quite figure it out.. This is how my directory looks.
My html code is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Krishi Mitra Admin Login</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Exo:wght#200&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/logstyle.css">
<script src="assets/js/logmain.js"></script>
</head>
<body>
<section>
<div class="img">
<img src="assets/imgs/bg.jpg">
</div>
<div class="content">
<div class="form">
<h2>Login</h2>
<form action="/" method="post">
<div class="input">
<span>Username</span>
<input type="text" id="username">
</div>
<div class="input">
<span>Password</span>
<input type="password" id="password">
</div>
<div class="input">
<div class="submit">
<input type="submit" value="Sign In">
</div>
</div>
<span id="error"></span>
</form>
</div>
</div>
</section>
</body>
</html>
and app.js file is:
const express = require('express')
const bodyParser = require('body-parser')
const mysql = require('mysql')
var path = require('path')
const app = express()
const port = process.env.PORT || 3306;
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs'
})
connection.connect(function(error){
if (error) throw error
else console.log("connected to the database successfully!")
});
app.get("/",function(req,res){
res.sendFile(__dirname + "/index.html");
})
app.use(express.static(path.join(__dirname, 'public')));
app.post("/", function(req,res){
var username = req.body.username;
var password = req.body.password;
connection.query("select * from loginuser where user_name = ? and user_pass = ?",[username,password],function(error,results,fields){
if (results.length > 0) {
res.redirect("/dash.html");
} else {
res.redirect("/");
}
res.end();
})
})
app.get("/welcome",function(req,res){
res.sendFile(__dirname + "/dash.html")
})
app.listen(port, () => console.log(`Listening on port ${port}`))
I tried running xampp server using the admin panel on port 3306 but it wont let the node file run and shows the error that port is already in use..
I want this to open the dash.html file after login
The problem with your current setup is that you're telling your node server to listen for incoming connections on port 3306, and you're using that same port to try and connect to the database.
Change your app.js code like this, and it should work.
... // rest of the code
const port = process.env.PORT || 1234; // or any port not already in use
.... // rest of your code
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs',
port : 3306 // <== add the port for database connection
})
For this to work, you should have Xampp in the background, running the MySQL module on port 3306. Of course, if you change your port in Xampp (for whatever reason), you'd need to change it in your app.js file as well.

applying styling for markdown in express/nodejs

I'm trying to load a markdown file as a static file which should afterwards be rendered via a html file. My question now is how I am to apply CSS Styling. Here is my code for the index.js:
const express = require('express');
const bodyparser = require('body-parser');
const showdown = require('showdown');
const marked = require('marked');
const app = express()
app.use(express.static(__dirname + '/'));
app.use(bodyparser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.use(express.static('public'));
app.get('/article', (req,res)=> {
var markdown = require("markdown-js");
var fs = require("fs");
var path = __dirname+'articles/article.md'
app.use(express.static("public"));
fs.readFile(path, 'utf8', function(err, data) {
if(err) {
console.log(err);
}
//res.send(marked("" + data));
//console.log(result);
res.render('index.html');
});
});
// listen to port
const PORT= 3000;
app.listen(process.env.PORT || 3000, function(){
console.log('server is running on port 3000');
})
The code for my current html file looks the following such that index.html:
<!DOCTYPE html>
<html lang="en">
<script src="style.css"></script>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<% result %>
</body>
</html>
In order to use variables you have to use ejs you can read about it here https://ejs.co/
then you can do something like this:
First change the name to index.ejs
Then you have to pass the data
res.render("index", { result: data })

res.send Not sending any data - Express.js

So I am working on this calculator app using Express.js and when I use the res.send Method I am not receiving any kind of response now.
I expect my webpage to send me the sum as in the calculator.js file.
I am using nodemon as well.
This is HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form method="POST">
<input name='num1' placeholder='num1' type='text'>
<input name='num2' placeholder='num2' type='text'>
<button
type="submit" name="submit">Calculate</button></form>
<h1 class='answer'></h1>
</body>
</html>
This is calculator.js
const express = require('express');
const app = express();
const port = 3000;
const bodyParser = require("body-parser");
const {
json,
urlencoded
} = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html")
});;
app.post("/", function (req, res) {
console.log(req.body);
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var sum = num1 + num2;
res.send(sum);
});
app.listen(port, () => console.log(`Example app listening on port port!`))
you can't use res.send() to send number, it will be sent as a http status code. You can simply convert calculated sum to string and then send it:
res.send(sum.toString())
res.send has been deprecated in the latest version of Express (4.17.1).
Using res.sendStatus instead solved my problem.

Socket.io Connection Event Not Triggering

I am new to using socket.io and I have tried to set up a basic functionality according to the docs and youtube tutorials. My program is supposed to console log "New socket connection" when I navigate to the index page. However, the event is not triggering. Am I missing something? Thanks!
My app.js file
const express = require("express");
const socket = require("socket.io");
const http = require("http");
const moment = require("moment");
const app = express();
const server = http.createServer(app);
const io = socket(server);
app.set("view engine", "ejs");
// Set static folder
app.use("/public", express.static("public"));
app.get('/', (req, res) => {
console.log("Reached index page")
res.render("index")
});
app.get('/room', (req, res) => {
console.log("Reach room page")
res.render("room")
});
// Run when a client connects
io.on("connection", (socket) => {
console.log("New socket connection")
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running. Navigate to localhost:${PORT}`));
My index.ejs file
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<link rel="icon" href="../public/">
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="../public/index/css/index.css" />
</head>
<body>
click here
<script>
var socket = io(); // this line is supposed to be sufficient to trigger
// the socket connection
</script>
<script src="../routes/index.js"></script>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
The error resulted from my naming my variable 'socket' when importing the socket.io dependency. The socket param in the line 'io.on("connection", (socket)' is supposed to reference another socket variable not the one that I created. Common practice is to name the dependency variable 'socketio' instead of 'socket'

Post Request not Calle

So I'm learning node.js and I've hit a wall. My post request is not getting triggered.
var http = require('http');
var express = require('express');
var app = express();
var fs = require('fs');
Setting up server
var server = http.createServer(function(req,res){
console.log('request was made: ' + req.url);
if (req.url === '/home' || req.url === '/'){
fs.readFile("./index.html",null,function(error,data){
if (error) throw error;
res.write(data);
res.end();
});
} else {
console.log("404");
}
})
The post-request that refuse to work
app.post('/test', function(req,res){
console.log("post req came thru");
})
Listening...
server.listen(8080)
HTML
<!DOCTYPE html>
<html>
<head>
<title>CRUD App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="/test" method="POST" >
<input type="text" name="test"></input>
<button>Submit</button>
</form>
</body>
</html>
You need to pass the Express app as a parameter to the http.createServer function otherwise it won't be handling any of your requests. Either that, or use the actual app.listen method:
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Categories