I want get username when user post it, but io.sockets.emit is not working. However, When i didn't put io.sockets.emit on app.post, It is working.
my html
<html>
<body>
<form action="chat" id="main" method="post">
<div>
<input type="text" id="id" name="username" value="" placeholder=" " required />
<label for="id">暱稱</label>
</div>
<div>
<input type="text" id="key" name="key" value="" placeholder=" " />
<label for="key">房號</label>
</div>
<button type="submit" value="加入房間" class="btn">加入房間</button>
</form>
</body>
</html>
my js
io.on('connection', (socket) => {
socket.on('joinRoom', username => {
console.log(username);
console.log("joinRoom");
});
socket.on('chat message', msg => {
const user = getCurrentUser(socket.id);
console.log(user);
io.emit('chat message', msg);
});
});
app.post('/chat', urlencodedParser, function (req, res) {
io.sockets.emit('joinRoom', "aa")
console.log(req.body)
res.sendFile('public/chat.html', { root: __dirname })
});
'joinRoom' seems not receive anything.
Related
So,here's my index.html file which consists of username and password input fields.So,when the user clicks on the submit button I want to get a alert saying "Welcome"+username.Im using nodejs also here. please help me.
index.html
<body>
<main class="form-signin">
<form method="post" action="/">
<h1 class="h3 mb-3 fw-normal">Login</h1>
<br/>
<div class="form-floating ">
<input type="name" class="form-control" name="username" placeholder="Enter Username...">
<label for="floatingInput">Username</label>
</div>
<div class="form-floating">
<input type="password" class="form-control" name="password" placeholder="Enter password">
<label for="floatingPassword">Password</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
</form>
</main>
</body>
Here's my server.js file where all the routes has been handled.
So below here when i click the submit button im getting the value of username entered in post request But how exactly should I create an alert?
server.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
res.sendFile(__dirname+"/index.html");
});
app.post('/', function(req,res) {
var username=req.body.username;
// I don't know what to do here exactly
});
app.listen(3000,() => {
console.log("Server started on port 3000");
});
So I am following a YouTube Tutorial on how to set up a simple login server (channel name: web dev simplified, video: "Node.js Passport Login System Tutorial")
The code (at the stage I am at # 14:12 mark in video) is suppose to console-log an array of a new registered user at the terminal.
but I get an empty array instead. Despite having the same code (I followed him step by step) I do not get the new user. What am I doing wrong?
const path = require('path');
const fs = require('fs');
const express = require('express');
const app= express();
const bcrypt = require('bcrypt');
const session = require('express-session');
// Get express ready to setup server
var users =[];
//{id:"", name:"", email:"", password:"",}
app.set('view-engine', 'ejs')
app.use(express.urlencoded({ extended: false }));
// Sets up main page
app.get('/', (req, res) => {
res.render('index.ejs', {name: 'Moe'})
})
////////////////Sets up login page////////////////////////
app.get('/login', (req, res) => {
res.render('login.ejs')
})
///////////////Sets up register page////////////////////////
app.get('/register', (req, res) => {
res.render('register.ejs')
})
///////////////////// Recieves date from register /////////////////
app.post('/register', async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
users.push({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
res.redirect('/login')
} catch {
res.redirect('/register')
}
console.log(users);
});
///////////////////////////////////////////////////////
// Setup Server
app.listen(5000);
html for login
<h1>Login</h1>
<form action="register" method="post">
<div>
<label for="name">username</label>
<input type="text" id="name" name="name" required>
</div>
<br>
<div>
<label for="name">password</label>
<input type="text" id="password" password="password"required>
</div>
<br>
<button type="submit">Login</button>
<br>
Register
</form>
<br>
back to Homepage
html for register
<h1>register</h1>
<form action="register" method="POST">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
</div>
<br>
<div>
<label for="email">email</label>
<input type="email" id="email" name="email" required>
</div>
<br>
<div>
<label for="password">password</label>
<input type="password" id="password" password="password"required>
</div>
<br>
<button type="submit">Register</button>
<br>
Login
</form>
<br>
back to Homepage
The request body needs to be parsed. Add this above your routes:
app.use(express.json());
^^^ Scratch this part. It's only needed with a JSON payload ^^^
In your html you have password="password" instead of name="password" for the password input element.
Why is the form data not being stored in req.body?
EJS/HTML
<form onsubmit="EditJob()" class="editForm">
<div class="form-group-edit">
<label for="position">Position</label>
<input type="position" id="position" name="position" class="form-control" placeholder="Enter Position Title"
/>
</div>
<div class="form-group-edit">
<label for="company">Company</label>
<input type="company" id="company" name="company" class="form-control" placeholder="Enter Company Name"
/>
</div>
<button type="submit" class="edit">
<i class="fas fa-plus"></i>
</button>
</form>
Client JS
const EditJob = () => {
const id = ####;
const url = `http://localhost:5000/dashboard/${id}`;
axios.put(url).then(res => {
console.log(res);
});
};
Server JS
router.put("/:id", (req, res) => {
Job.findByIdAndUpdate(req.params.id, {
position: req.body.position,
company: req.body.company,
status: req.body.status
})
...
...
});
Updated doc in my database results in {position: null, company: null, status: null}..
Make sure you're using body-parser, or set your express middleware like code below:
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
⚠️ When you're using axios.put(), make sure you passing your data in there. You can read the documentation here
An Example: Axios Put
axios.put(endPoint, data, config).then(...).catch(...)
I hope it's can help you.
I need to get the data entered in the input text. Using document.getElementById, but displays the error: ReferenceError: document is not defined.
That is, I need to click on the button i get all the data that the user entered.
.........................................................................
.........................................................................
.........................................................................
.........................................................................
.........................................................................
.........................................................................
const express = require('express');
const router = express.Router();
const Cookies = require('cookies');
router.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
// console.log(res.headers(['cookie']));
// res.setHeader('Set-Cookie', 'TestHeader=HeaderValue');
const cookies = new Cookies(req, res);
if (req.url === '/favicon.ico') {
res.end();
return;
}
cookies.set('admin', 'true');
console.log(cookies.get('node'));
res.end(`
<!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>Document</title>
<script src="signUp.js" defer></script>
</head>
<body>
<h1>Sign Up Form</h1>
<form method="POST" action="/sign-up" autocomplete="off">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" required autocomplete="off">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="email" id="email" required autocomplete="off">
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" required autocomplete="off">
</div>
<div>
<label for="password_confirmation">Password again</label>
<input type="password" name="password_confirmation" id="password_confirmation" required autocomplete="off">
</div>
<button id="sign_up_btn">Sign Up</button>
</form>
Sign In
</body>
</html>
`);
const userName = document.getElementById('name');
const userEmail = document.getElementById('email');
const userPassword = document.getElementById('password');
const userData = [userName, userEmail, userPassword];
for (let i = 0; i < userData.length; i += 1) {
console.log(userData[i]);
}
});
router.post('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.statusCode = 501;
res.end('Not implemented yet!...');
});
module.exports = router;
please place the script before </body>, or in window.onload callback function. Because document object is not created when you call document.getElementById
You've edited your question so allow me to edit my answer:
Your implementation here is incorrect. You are using Express to serve a webpage with a form. In order to evaluate the values of the form, you'll need to decide if you want to do that on the client side or the server side.
Your form looks like a login form, so you'll want to process this on the server side.
const express = require('express');
const router = express.Router();
const Cookies = require('cookies');
const bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded());
router.use(bodyParser.urlencoded({ extended: true }));
router.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
// console.log(res.headers(['cookie']));
// res.setHeader('Set-Cookie', 'TestHeader=HeaderValue');
const cookies = new Cookies(req, res);
if (req.url === '/favicon.ico') {
res.end();
return;
}
cookies.set('admin', 'true');
console.log(cookies.get('node'));
res.end(`
<!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>Document</title>
<script src="signUp.js" defer></script>
</head>
<body>
<h1>Sign Up Form</h1>
<form method="POST" action="/sign-up" autocomplete="off">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" required autocomplete="off">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="email" id="email" required autocomplete="off">
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" required autocomplete="off">
</div>
<div>
<label for="password_confirmation">Password again</label>
<input type="password" name="password_confirmation" id="password_confirmation" required autocomplete="off">
</div>
<button id="sign_up_btn">Sign Up</button>
</form>
Sign In
</body>
</html>
`);
router.post('/sign-up', (req, res) => {
const { name, email, password } = req.body;
// do stuff with name, email, password
});
});
router.post('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.statusCode = 501;
res.end('Not implemented yet!...');
});
module.exports = router;
For client side form processing, you could do something like this:
HTML
<form action="#" onsubmit="handleSubmit(this)">
<input type="text" name="foo" value="bar" />
<input type="submit" value="Submit" />
</form>
Javascript
function handleSubmit(e) {
console.log(e.foo.value)
}
Example
I am trying to insert registration data into MySQL using HTML and JS in Visual Studio.
I am able to view the webpage, click on the sign-up link and complete the registration form. The problem occurs when I press submit (sign-up). The page returns to the main webpage and nothing is added to the database. I receive no error messages or anything.
The code for the form is:
var mysql = require('mysql');
var express = require('express');
var app = express();
var server = null;
var con = mysql.createConnection({
host: "localhost",
user: "Personal",
password: "****************",
database: "Personal"
});
app.get('/api/users', function(req, res) {
con.query("SELECT * FROM users", function(err, result, fields) {
if (err)
return console.trace('fatal error: ' + err.message);
res.json(result);
});
});
app.get('/index', function(req, res) {
res.sendfile('index.html', {
root: __dirname + '/public'
});
});
app.use('/static', express.static('public'))
app.get('/', function(req, res) {
res.sendfile('index.html', {
root: __dirname + '/public'
});
});
con.connect(function(err) {
if (err)
return console.trace('fatal error: ' + err.message);
server = app.listen(5000, function() {
console.log('Server is running..');
});
});
app.post('/signup', function(req, res) {
var fname = req.body.fname;
var lname = req.body.lname;
var company = req.body.company;
var email = req.body.email;
var contact = req.body.contact;
res.write('You sent the fname "' + req.body.fname + '".\n');
res.write('You sent the lname "' + req.body.lname + '".\n');
res.write('You sent the company "' + req.body.company + '".\n');
res.write('You sent the email "' + req.body.email + '".\n');
res.write('You sent the contact "' + req.body.contact + '".\n');
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO form (fname, lname, company, email, contact) VALUES ('" + fname + "', '" + lname + "', '" + company + "', '" + email + "', '" + contact + "')";
con.query(sql, function(err, result) {
if (err) throw err;
console.log("1 record inserted");
res.end();
});
});
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Personal</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="static/index.css">
<body>
<div class="header">
<h1>Personal</h1>
<P>Personal</P>
</div>
<button onclick="document.getElementById('id01').style.display='block'" style="width:25%;" class="center">Login</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal1-content">
<div class="container1">
<h1>Login</h1>
<p>personal</p>
<hr>
<label for="Username"><b>Username</b></label>
<input type="text" placeholder="Username" name="Username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Password" name="psw" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<br />
<input type="submit" value="login" class="login" />
</div>
</div>
</form>
</div>
<script>
var modal = document.getElementById('id01');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<button onclick="document.getElementById('id02').style.display='block'" style="width:25%;" class="center">Sign-up</button>
<div id="id02" class="modal1">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal1">×</span>
<form class="modal1-content">
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<form action="/signup" method="POST">
<label for="fname"><b>First Name</b></label>
<input type="text" placeholder="Enter First Name" name="first name" required>
<label for="lname"><b>Last Name</b></label>
<input type="text" placeholder="Enter Last Name" name="lname" required>
<label for="company"><b>Company</b></label>
<input type="text" placeholder="Enter Company" name="company" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="contact"><b>Contact Number</b></label>
<input type="text" placeholder="Enter Contact Number" name="contact" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<input type="submit" value="Sign-up" class="signup" />
</div>
</div>
</form>
</form>
</div>
</form>
</form>
<script>
var modal1 = document.getElementById('id02');
window.onclick = function(event) {
if (event.target == modal1) {
modal1.style.display = "none";
}
}
</script>
</body>
</head>
</html>
How can I fix this?
You need to specify the URL of the end point you want to submit the data to with the action attribute and the method with the method attribute:
<form class="modal1-content" action="/signup" method="post">
The defaults are the current page and GET respectively, which is why submitting the form just reloads the main page.