Node.js (express framework): Post method not working - node.js

I am able to run the Get method and HTML form also visible on browser using Get method but when I am clicking on submit button nothing is happening, no error nothing. it shows the same HTML form page.
HTML code:
<!DOCTYPE html>enter code here
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form action="/" method="post">
<h1>Calculator</h1>
<input type="text" name="num1" placeholder="Number 1">
<input type="text" name="num2" placeholder="Number 2">
<button action="/" type="button" name="button">Submit</button>
</form>
</body>
</html>
Node Js code:
//jshint esversion:6
const express=require("express");
const app=express();
app.get("/", function(req,res){
res.sendFile( __dirname+"/index.html");
});
app.post("/", function(req,res){
res.send("Thanks for post");
});
app.listen(3000, function(){
console.log("Server Started On Port 3000");
});

Your button type should be Submit
<button type="submit" value="Submit">Calculator</button>

Related

socket console.log() not showing when connected

I'm completely new to socket.io and I'm trying to connect a client to the server.
This is app.js.
const socketio = require("socket.io");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index");
});
const server = app.listen(process.env.PORT || 3000, () => {
console.log("server is running...");
});
// Initialize socket for the server
const io = socketio(server);
io.on("connection", socket => {
console.log("New user connected");
});
This is index.ejs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Real time Chat App</title>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
/>
</head>
<body>
<div class="container">
<div class="title">
<h3>Realtime Chat Room</h3>
</div>
<div class="card">
<div class="card-header">Anonymous</div>
<div class="card-body">
<div class="input-group">
<input
type="text"
class="form-control"
id="username"
placeholder="Change your username"
/>
<div class="input-group-append">
<button class="btn btn-warning" type="button" id="usernameBtn">
Change
</button>
</div>
</div>
</div>
<div class="message-box">
<ul class="list-group list-group-flush" id="message-list"></ul>
<div class="info"></div>
</div>
<div class="card-footer">
<div class="input-group">
<input
type="text"
class="form-control"
id="message"
placeholder="Send new message"
/>
<div class="input-group-append">
<button class="btn btn-success" type="button" id="messageBtn">
Send
</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script src="/js/chatroom.js"></script>
</body>
</html>
This is chatroom.js.
(function connect() {
let socket = io.connect("http://localhost:3000")
})();
The problem is I don't know why io.on("connection", socket => { console.log("New user connected"); }); not working here. Everything seems to be OK in Google Chrome console, but the message doesn't appear in VS code terminal when I go to localhost website. The terminal always looks like this when I refresh the page.
vs code terminal
Is there anything wrong with my code?
I solved it already. I change <script src="https://cdn.socket.io/socket.io-1.0.0.js"></script> to <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.js"></script> and still have no idea what the problem is ,but it works.
I think it's a cors origin problem, use Firefox to see it in the console
And that't how you can resolve it : socket.io, 'Access-Control-Allow-Origin' error

TypeError: Cannot read property of 'db' undefined

I am new coder and developing To-Do App. I want to connect my app to mongoDB Atlas database from VSC editor Terminal. I use Node.js (Express) and mongoDB Atlas. When I uninstall Node.js and start code from scratch, it works fine because code is all OK but next day when I get back to the same project and run it, it doesn`t work anymore. It shows up an error. You may check this terrible error here on this link: https://prnt.sc/u8paeg
let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db
let connectionString ='mongodb+srv://akhtarayaz:SpreadLoveEverywhere#cluster0.yfwfa.mongodb.net/Users?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
db = client.db()
app.listen(3000)
if (err) {
throw err;
}
})
app.use(express.urlencoded({extended: false}))
app.get('/', function(req, res){
db.collection('accounts').find().toArray(function(err, accounts){
res.send(`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple To-Do App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1 class="display-4 text-center py-1">To-Do App</h1>
<div class="jumbotron p-3 shadow-sm">
<form action="/create-account" method="POST">
<div class="d-flex align-items-center">
<input name="account" autofocus autocomplete="off" class="form-control mr-3" type="text" style="flex: 1;">
<button class="btn btn-primary">Add New Item</button>
</div>
</form>
</div>
<ul class="list-group pb-5">
${accounts.map(function(account){
return `<li class="list-group-item list-group-item-action d-flex align-items-center justify-content-between">
<span class="item-text">${account.text}</span>
<div>
<button class="edit-me btn btn-secondary btn-sm mr-1">Edit</button>
<button class="delete-me btn btn-danger btn-sm">Delete</button>
</div>
</li>`
}).join('')}
</ul>
</div>
</body>
</html>
`)
})
})
app.post('/create-account', function(req, res){
db.collection('accounts').insertOne({text: req.body.account}, function(){
res.redirect('/')
})
})

GET method form with ExpressJS - multiple app.get

I want to make a simple login form.
This is the relevant code:
app.get('/login' , (req,res)=>{
app.use(express.static('login'));
res.render(__dirname + '/login/index.ejs');
/*This is load the login page*/
});
index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>login</title>
</head>
<body>
<h1>Login</h1>
<form action="/" method="GET">
<input type="text" name="email" placeholder="email">
<input type="password" name="password" placeholder="password">
<input type="submit" value="login">
</form>
</body>
</html>
You can see the form is GET method because I don't create/update anything. If I used app.post for detecting the parameters I've used app.post and it was working fine.
But how I handle two app.get ? one for load the page, the second for handle the html form ?
For example:
app.get('/login' , (req,res)=>{
console.log(req.query);
}
Thanks !
I recommend that instead of using the GET method for both the login and the displaying of your website you make your form method POST instead of GET. Then use multer in your express app as a way to parse the received form data.
<form action="/" method="POST">
const multer = require('multer');
const upload = multer();
app.use(upload.array());
app.post('/login', function(req, res){
console.log(req.body);
res.send("recieved your request!");
});

EJS shows red mark when trying to embed data

i have this node server with express which directs data to different files like .ejs files and it worked before but I dont know what I did and so that it doesnt work, it marks every ejs's "<" in red.
im using VS CODE.
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.send("Hello wassup");
});
app.get('/homepage/:name', function(req,res){
res.render('home', {fullname : req.params.name});
});
app.get('/profile/:name', function(req, res){
var data = {Dummytext: "hey yo wassup and all that yea imma be right here tho",
hobbies : ['baskeall','computing','drawing', 'Learning', 'Driving'] };
res.render('profile', {fullname: req.params.name, data:data});
});
app.listen(4000);
and i have for example this ejs file that doesnt work
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>bla</title>
<link rel="stylesheet" type="text/css" href="partials/nav.css">
</head>
<body>
<% include partials/nav.ejs %>
<div class="user-info">
<div class="user-about">
<div class="user-name"><span><%= fullname %></span></div>
<div class="user-info_">
<div class="userimg">
<img src="/YDSign.png" alt="User profile" draggable="false" />
</div>
<div class="user-speech"><p><%= data.Dummytext%></p></div>
</div>
</div>
<div class="user-button">
<button type="button" class="friendAdd">Add Friend</button>
<button type="button" class="friendBell">Bell</button>
</div>
<div class="user-hobbies">
<div class="hobbies-list">
<h1>Hobbies</h1>
<div class="Upscroll"><img src="/iconList/ArrowUp.png" draggable="false"/></div>
<ul>
<% data.hobbies.forEach(function(item){ %>
<li><a><%= item %></a><img src="iconList/Hobbies.png" class="ident" /></li>
<% }); %>
</ul>
<div class="Downscroll"><img src="/iconList/ArrowDown.png" draggable="false" /></div>
</div>
</div>
</div>
Everything is fine.
You just should install plugin EJS language support in VSCode.
Just click CTRL+SHIFT+X and then write ejs in the search bar after that install the first one.
That works for me.

NodeJS - Getting form post data

I am a newbie in NodeJs.
Trying to figure out why the following code is not working for me.
I am basically trying to do a simple post from an HTML file.
It works fine if I send the post request from curl, or if I use AJAX post.
Would like to know what's wrong with the following post.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post" action="http://localhost:3000/">
<table>
<tr>
<td><input type="text" id="txtOne"/></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit Data">
</td>
</tr>
</table>
</form>
</body>
</html>
My node.js file is
var express = require("/usr/local/bin/node_modules/express");
var bodyParser = require("/usr/local/bin/node_modules/body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/',function(req,res){
res.sendfile("mypage.html");
});
app.post('/',function(req,res){
var str = req.body.txtOne;
console.log("From Client POST request: Text = " + str);
res.end(str);
});
app.listen(3000);
I am getting str value as undefined.
First of all, your form field needs a name value instead of a id.
So change
<td><input type="text" id="txtOne"/></td>
to
<td><input type="text" name="txtOne"/></td>
var str = req.body.txtOne;
you are searching for the input that has name="txtOne"
id works only for the DOM
<td><input type="text" name="txtOne"/></td>

Resources