how can I make the client talk to the express server? - javascript

So I am trying to link this interface to a server so that the message I input in the front end is Posted in a separate webpage hosted on the server. eg "Hello [name]"
This is the interface:
<form id="loginformA" action="userlogin" method="post">
<div>
<label for="Insert message here">Message: </label>
<input type="text" id="message" name="message"></input>
</div>
and this is the server I am trying to post the message to:
var express = require('express');
var app = express();
app.use(express.static('public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/userlogin", function(request, response) {
response.send( "Hello " + request.body.message );
});
app.listen(process.env.PORT || 8080, process.env.IP);
I am just not sure how to make the interface and server talk to each other. I would also like to store all the messages in a db too, but that is for later after I figure this out.
Thanks!

Right now your form submits to /userlogin. You should define that route in your server like this:
app.post('/userlogin', function(req, res){
res.send('Hello' + req.body.message);
}
req.body is basically the post data submitted by your form, in this case only the input named 'message.'
any time you wish to submit a form to a node server, ensure the action corresponds to a route or method with an identical name.

From your html ...
app.post('/userlogin', function(request, response) {
response.send( "Welcome, your message is: " + request.body.message );
});

Related

Process form submit response from express server with javascript

(Please correct my terminology if it's not correct.)
My files server.js, run.js and index.html, are in the same directory.
server.js
Sets up the server.
const express = require('express');
const path = require('path');
const run = require('./run.js');
var app = express();
app.get('/index.html', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/', function(req, res){
res.redirect('index.html');
});
app.post('/run', async function(req, res){
var data = await run.run();
res.json(data);
});
app.listen(5000, function () {
console.log('Dev app listening on port 5000');
});
run.js
Will contain functions that consumes time. Here just one function as example:
async function run(){
//do time consuming stuff
var data = {
"status" : "ok",
"a1" : 1,
"a2" : 2
};
return data;
}
module.exports = {
run:run
}
index.html
Simple form.
<!DOCTYPE html>
<html>
<body>
<form id="search-form" action="/run" method="post">
Input:<br>
<input type="text" name="input1" id="input1" value = ""> <br>
<input type="submit" value = "Run">
</form>
<script></script>
<div id="data"></div>
</body>
</html>
When I run the server, go to localhost:5000 in the browser, and click the run button, I get redirected to a page just showing the content of data.
What I would like to happen when I click the the run button is;
The server process /run post request
A response is sent with res.json or res.send to the client
A javascript script on the client side should catch the response, process it, and make some change to the html code (in my case, create some table).
How can I achieve this?
So your problem is that you're using a form. Forms will redirect you to the specified web page with all of the form's data.
You need an XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("POST", "/run", true);
xhr.send();
If you ever need the data of your form to be submitted as well, I have some documentation on how to do that.
Hope this helps!

Empty body when submitting html form

I have a simple NodeJs app, and trying to build a simple authentification form. But for some reason, i'm not able to get the entred data in the form. Here's my code :
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser= require ('body-parser');
var user = require('./routes/user');
var login = require('./routes/login');
var jwt = require('jsonwebtoken');
var app = express();
app.use(bodyParser.json());
app.use(cookieParser());
app.get('/userprofile', user.getUserInfos);
app.post('/users', user.createUser);
app.get('/login', function (req, res) {
var html='';
html +="<body>";
html += "<form action='/login' method='post' name='logingorm' enctype=\"application/json\">";
html += "Username:<input type= 'text' name='username'><br>";
html += "Password:<input type='password' name='password'><br>";
html += "<input type='submit' value='submit'>";
html += "</form>";
html += "</body>";
res.send(html);
});
app.post('/login', user.login);
app.listen(3000);
console.log('Listening on port 3000...');
And then, the login function called when a post is received on /login :
exports.login= function(req, res) {
console.log(req.body);
}
Always get {} as result of my console.log
Any idea ?
Thanks a lot
application/json is not a valid form encoding. When the browser sees that, it falls back to application/x-www-form-urlencoded.
bodyParser.json() ignores requests with MIME types other than application/json, and even if it didn't, it wouldn't be able to parse the urlencoded data. Use bodyParser.urlencoded() instead.
app.use(bodyParser.urlencoded({extended: false}));
I think that might be because there is no 'value' attribute written for both the input tags. Try writing them and check.

Send new HTML page and make GET request to it after POST request from original page

I'm new to Node.js and JavaScript. I have a specific problem but mostly need advice on the best solution.
I'm running a Node server. I want the client to be able to submit a string to the server, then the server to display a new HTML page that shows the string data.
I'm using Express and Socket.io.
In the following files, the client sees index.html, then after submitting the form it sees return.html. I print the input string to the console, and the output is as expected (whatever the user enters). But the return.html is never updated with the input string.
I also tried sending the return.html page and the change_result call in an async series, but the sendFile function never ends and the second function in the series is never called. In previous attempts it worked intermittently with a setTimeout around the emit('change_result') function.
Why doesn't the call to change_result do anything? I used the same technique to update the headings of the original index.html in previous versions. Should I be routing to localhost.../return.html and sending the post data there, or something like that?
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser') //for POST request
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
server.listen(8080, function() {
console.log("Server running on port 8080.");
});
var dir = __dirname;
app.get('/', function(req, res) {
res.sendFile(dir + '/index.html');
});
app.post('/', function(req, res) {
var query1=req.body.input1
console.log("Server: In post request.")
console.log(query1);
res.sendFile(dir + '/return.html');
io.emit('change_result', {
result: query1
});
});
index.html
<!DOCTYPE html>
<html>
<body id="body">
<form method="post" action="http://localhost:8080">
String: <input type="text" name="input1" id="input1" />
<input type="submit" id="button1" value="Submit" />
</form>
</body>
</html>
return.html
<!DOCTYPE html>
<html>
<body id="body">
<p id="heading1">Result: </p>
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io();
socket.on('change_result', function(data) {
document.getElementById('heading1').innerHTML = "Result: \""+data.result"\"";
});
});
</script>
</body>
</html>
I'm not knee-deep inside socket.io, but IMO the problem is, that the server has no way to know if any listeners are ready.
I think you should emit a 'ready' event, once the return.html is loaded, then listen to 'change_result'. Also separate the socket communication from the POST response on the server. Like so.
server.js
var query;
app.get('/', function(req, res) {
res.sendFile(dir + '/index.html');
});
app.post('/', function(req, res) {
query = req.body.input1;
console.log("Server: In post request.");
console.log(query);
res.sendFile(dir + '/return.html');
});
io.on('connection', function(socket) {
socket.on('ready', function() {
socket.emit('change_result', {result: query});
});
});
return.html
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io();
socket.emit('ready', function(data) {});
socket.on('change_result', function(data) {
document.getElementById('heading1').innerHTML = "Result: \""+data.result + "\"";
});
});
</script>

Twilio call button and user input

so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.
const express = require("express");
const app = express();
const port = 2222;
app.get("/", function(req, resp){
resp.end("welcome to my app");
});
app.get("/:data", function(req, resp){
var accountSid = 'accountSid'
var authToken = 'authtoken'
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
})
console.log(req.params.data);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: "+req.params.data);
}
});
app.listen(port, function(err){
if(err){
console.log("error starting "+err);
return false;
}
console.log("port is running. "+port);
})
Twilio developer evangelist here.
You're most of the way there with what you want to achieve. You can absolutely create a form that will take an input from a user and dial the number they enter.
First up, You will want to update your route as the number you send through a form won't be a part of the path, instead it will come as part of the body of the request. In order to read request bodies in express, you will want the body-parser module. So, install that in your project with:
npm install body-parser --save
Then include it in your file and use it with your app:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
Now, form's usually POST their data, rather than working over GET, so let's update your route to receive that POST request and extract the number from the request:
app.post("/calls", function(req, resp) {
const accountSid = 'accountSid'
const authToken = 'authtoken'
const client = require('twilio')(accountSid, authToken);
const number = req.body.number;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: number,
from: '6043302056',
}, function(err, call) {
if(err) {
console.error(err);
} else {
console.log(call.sid);
}
})
console.log(number);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: " + number);
}
});
Now, you need an HTML file that will include a form to make the request to this endpoint. Create an HTML file called index.html and place it in a new folder in your application called public.
You can load static files from the public directory in express with this line, add it near the top, after you create the app:
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
Finally we just need the HTML. This is the simplest HTML I could write that would do what you need:
<!DOCTYPE html>
<html>
<head>
<title>Make a call</title>
</head>
<body>
<form action="/" method="POST">
<label for="number">What number do you want to call?</label>
<input id="number" type="tel" />
<button type="submit">Make call</button>
</form>
</body>
</html>
As you can see it is just a form with a single input, the number, and a button to submit it.
Give this all a go and let me know how you get on.
Yes,
first: you can do that, but you need to write the code in HTML File or at least include this code in html file, and call the Twilo's function after you click on the respective button. For that first, render a HTML page, after user enters the address, on that HTML Page give input number and call now button feature. and after user clicks on the button, do:
function callNow() {
var num = document.getElementById('number').value;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: num,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
{
Your HTML Code should be:
<input id="number">
<button onclick="callNow()">Call Now</button>
You can include twilio cdn and use this feature. I am just giving you the concept, I hope you will find this helpful.

browser display error after request node.js

i am trying to insert some data to database using node and mysql i manage to get it done, but after query response the browser loads continuously i tried pooling still nothing happens
Here is my code
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var sql = require('mysql');
var pool = sql.createPool({
host : 'localhost',
user : 'root',
password : '',
port : '3306',
database : 'node'
});
app.get('/nodeThis', function (req, res) {
res.sendFile(__dirname + '/insert.html');
});
app.post('/nodeThis', urlencodedParser, function (req, res) {
var post={user_name:req.body.name1,user_what:req.body.what,user_why:req.body.why};
pool.getConnection(function(err, connection){
connection.query('INSERT INTO user SET ?', post, function(err){
if(err){
console.log(err);
}else{
console.log('succes');
}
});
connection.release();
});
});
server.listen(3000);
Here is how i pass the data from HTML to node
<html>
<body>
<div>
<form action="/nodeThis" method="post">
<input type="text" name="name1">
<input type="text" name="what">
<input type="text" name="why">
<button class="boom">Submit</button>
</form>
</div>
</body>
</html>
After the database operation, you aren't sending any response to the browser; you just sent an output to the console instead; the browser was waiting for a response that never came
If you insert res.sendFile(__dirname + '/insert.html'); or some other response after the console.log('succes');, you'll see an output on the browser.
That being said, I hope this is just a proof of concept and not a production code.
Update Based on the Comment
Retrieving the number of rows affected
After running the executing the database insertion function
db.query("insert into table", [data-to-insert], function(err, result){
//to retrieve the number of rows affected
var number_of_rows = result.affectedRows
})
the result has a property called affectedRows that allows the user to know how many rows were inserted, updated, or deleted.
To retrieve the primary id of the inserted row (if it has one), result has a property called insertId.
var id = result.insertId
Hope this helps!

Categories