NodeJS - socket.on doesn't appear to be called - javascript

I am using the Node.JS POST method to submit a form to my server. It is transmitted to the server fine; no problems occur at this stage. However, when I use io.emit with socket.io to transfer the data back to the client, nothing seems to happen client-side. Nothing is printed to the console and I'm getting no errors there or in Command Prompt (where I'm running the server from).
index.html:
<form id="schoolCreateForm" action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});
</script>
app.js:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var io = require('socket.io')(serv);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post('/createSchool', function(req, res) {
response = {
school_name: req.body.schoolName,
school_private: req.body.schoolPrivate,
entry_password: req.body.entryPassword
};
console.log(response);
res.sendFile(__dirname + '/client/index.html');
io.emit('updateSchool', response);
});
serv.listen(3000);
console.log("Server started on localhost://3000");
Does anyone know what's going on?

<form action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit" id="schoolCreateForm">Submit</button>
After submitting your form data it will reload your page, it means socket connection will be ended. If you want to see a response with socket make ajax.post request without reloading the page.
<form id="schoolCreateForm">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
document.querySelector('#schoolCreateForm').addEventListener('click',
function(e) {
e.proventDefault() // this line will not all to reload page after
/// submitting the
//form data
### writh you ajax request functionality here
})
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});

Related

How to fix a "reload page loop" when using a post method in Node JS?

Given the following html form:
<form class = "new-date" method = "POST" action = "http://localhost:5600/postDate">
<h3>Owner</h3>
<input type ="text" name = "ownerName" class = "form-element global" id="owner">
</select>
<h3>Pet</h3>
<input type = "text" name = "petName" class = "form-element global" id = "pet">
</select>
<h3>Schedule the date</h3>
<input type="date" id="birthday" name="birthday" class = "form-element global" id="date">
<h3>Description</h3>
<textarea class = "form-element description-text" placeholder= "What is wrong with your pet?" name ="problem" ></textarea id="problem"><br>
<input type="submit" class = "form-element btn" value="Add">
</form>
Im trying to make a post method that is located inside my server.js (Node):
const exp = require('express');
const path = require('path');
var bodyParser = require('body-parser');
const app = exp();
/*DATABASE AND QUERIES*/
const mysql = require("mysql2");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "admin",
database: "control_clientes",
connectionLimit: 5
});
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.post('/postDate', (req, res)=>{
console.log(req.body.ownerName); //TO CHECK IF IM RECEIVING THE DATA. IT WORKS
});
After submitting and sending the client side data to my server, the html page is not properly doing the reload task:
As can see in this image, the reload thing is still going. I'm not sure why it does that.
Im new to Node JS, do you have any idea what is going on with the unfinished reload thing?
Try this
app.post('/postDate', (req, res)=>{
console.log(req.body.ownerName); //TO CHECK IF IM RECEIVING THE DATA. IT WORKS
res.json({message: 'OK.'})
});
If you want your browser to stop spinning (loading) you need to send a response from a server.
For example send a json response with req.body (echo endpoint)
app.post('postDate', (req, res) => {
console.log(req.body.ownerName);
res.json(req.body);
})

Form is not submitting in node

I am trying to make a post request from a html form and cant figure out where im going wrong.
> <form action="/api" method="POST">
<label for="username">username or email address</label>
<input name="username" id="username" type="text">
<label for="password">password</label>
<input id="password"name="password" type="text">
<button >Log in</button>
</form>
here is my main javascript file for the html (not the server)
"use strict"
let options = {
headers:{
"Content-Type" : "application/json"
},
method: "POST",
}
// fetch("/api",options)
And here is my node js server
"use strict"
//Installing express
let express = require(`express`)
let app = express()
app.use(express.json())
//running the server
app.listen(3000,()=>{
console.log("server is running boi");
})
//Middleware to load the static content
app.use(express.static(`public`))
//Database stuff
let Datastore = require('nedb')
let db = new Datastore({ filename: 'database.db' });
db.loadDatabase()
db.insert({username:"sid", password:"westham"})
//Handler for any post requests made
app.post(`/api`,(req,res)=>{
console.log("request was made");
console.log(req.body);
})
Two Observations
No middleware found in your server.js file for handling form data,
use body-parser http://expressjs.com/en/resources/middleware/body-parser.html
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true });
In your html form, if you're not submitting form with JavaScript then mentiod button type as submit
<button type="submit" >Log in</button>

Cross origin request block Node.js

i have a simple code that makes ajax interactions, it used to work perfectly about 1 week ago, but when i checked it today it says in the console : Blocking a Cross-Origin Request: The "Same Origin" policy does not allow the remote resource located at http://localhost:8080/api/user. Reason: CORS request failed.
I use firefox so i installed the plugin Cors everywhere, but no results yet.
My code :
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Hello World!</h1>
<div>
<h1>Sending User</h1>
<form id="userForm">
<label for="name">Name</label>
<input id="name" name="name"/>
<br/>
<label for="age">Age</label>
<input id="age" name="age"/>
<br/>
<input type="submit" value="Send"/>
</form>
</div>
<br/>
<br/>
<div>
<h2>Click the button below for getting User from server and showing it</h2>
<button id="getUserButton">Get User</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script>
$(document).ready(function () {
$('#userForm').submit(function (e) {
var user = {
name: $('input[name=name]').val(),
age: $('input[name=age]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/user',
data: user
})
.done(function (data) {
// clear form
$('input[name=name]').val('');
$('input[name=age]').val('')
alert(data);
});
e.preventDefault();
});
$('#getUserButton').click(function (e) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/api/user'
})
.done(function (data) {
alert(JSON.stringify(data));
});
});
});
</script>
</body>
</html>
test.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var userStoredInMemory = {};
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/api/user', function (req, res) {
res.json(userStoredInMemory);
});
app.post('/api/user', function (req, res) {
userStoredInMemory = req.body;
res.send('User was already stored from express.');
});
app.listen(8080, function () {
console.log('server up and running at 8080 port');
});

HTML/server function interaction (GET, POST)

I think I'm lacking some understanding of these fundamental concepts (I've read a decent amount of resources and examples) of how these functions work server-side and how the html interacts with them. I was writing methods earlier today and communicating between the server and html perfectly, manipulating an array I had stored locally on the server file. For reference I'll show you how I was doing it.
jQuery script in html file:
$.post("/deck", { name: "Angel of Fury", power: 666 }, function(){
});
server file:
var express = require('express'),
app = express(),
db = require('./db'),
bodyParser = require('body-parser'),
controller = require('./controller');
//add body parser middleware
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//Serves static pages
app.use(express.static(__dirname + ('/')));
//loads the html page
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var server = app.listen(3000, function () {
var host = server.address().address;
host = (host === '::' ? 'localhost' : host);
var port = server.address().port;
console.log('listening at http://%s:%s', host, port);
});
var deck = [ ];
app.get('/deck', function(req, res) {
res.send(deck);
});
app.post('/deck', function(req, res) {
console.log(req.body);
var card = req.body;
deck.push(card);
res.send(deck);
});
Given this code I could navigate to "localhost:3000/deck and any changes I made were stored in the array and displayed at this address. Simple enough. I've taken that a step farther and implemented a database, mySQL and have successfully written methods for insertion, select, delete, etc..
<script>
$("submit").on("click", function(){
$.post("/users", { name: username.value, password: psw.value, email: email.value}, function(){
console.log("post successful..");
});
});
</script>
<body>
<form>
username:<br>
<input type="text" name="username"><br>
password:<br>
<input type="password" name="psw"><br>
email:<br>
<input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
I added the above form jquery script to the html page. And attempted to add the server functions below.
app.get('/users', function (req, res) {
});
app.post('/users', function (req, res) {
console.log(req.body);
});
I thought that this would allow me to use the req.body object on submission of the form. Please correct me if I'm going about this the wrong way, I would be grateful for any help/tips.
You can do two things:
Use event.preventDefault() to stop the form submission.
Change the button type to button instead.
As you have not prevented the form to submit so, whenever you click the submit button it submits the form and it makes a default get request if method attribute to post is not been provided.
$("submit").on("click", function(ev){
ev.preventDefault(); // <-------- HERE
$.post("/users", { name: username.value, password: psw.value, email: email.value}, function(){
console.log("post successful..");
});
});
Or make a small change at your markup:
<input type="button"....../>
In the form.
As per your latest comment, add a class/id attribute to the button and change the selector:
<input type="submit" id="submit"...../>
Now in js you have to use this:
$("#submit") // <---- notice the # which denotes the ID selector in jQuery.

Unable to send form data to server side (nodejs) using ajax

I am trying to send form data via ajax to a nodejs server. Previously asked on this post.
Here's what my code looks like:
<div id="inputid" style="width: 400px; height:400px">
<p> Please enter a value between -90 and 90 for lat, and -180 and 180 before hitting
submit.</p>
<form id="sendCoordinates" action="http://localhost:8080/geodata" method="post">
MinLat: <input type="text" name="MinLat" value="15" id="minlat"><br>
MaxLat: <input type="text" name="MaxLat" value="25" id="maxlat"><br>
MinLong: <input type="text" name="MinLong" value="-10" id="minlong"><br>
MinLong: <input type="text" name="MaxLong" value="120" id="maxlong"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$(document).ready(function() {
console.log("hi hi");
$("#sendCoordinates")
.on('submit', function(e) {
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray();
$.each(params, function(i, val) {
// console.log(val);
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
console.log("hi helo");
}
});
});
});
</script>
</div>
My server side code looks like this :
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
// for debugging purposes, just logging the request to check
// if request received
app.post("/geodata", function(req, res) {
console.log("hey");
console.log(req.body);
res.send("hi back!");
});
I am trying this out but I am unable to send the form successfully, and upon hitting submit, I get "hey" and an empty {} as logged output. I am not able to log the formData on the client side, regardless.
Can someone point out what I might be doing wrong?
You didn't assign a form to formData() that's why you're not sending any data to the server.
var myForm = $('#sendCoordinates')[0];
var formData = new FormData(myForm);

Categories