Error shows when trying send request as form data - javascript

This is a simple calculator that can add numbers.
The html form loads correct to the browser but then once I submit the form, I get a 404 error code
Error code : Cannot POST /index.html
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form action="index.html" method="post">
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<button type="submit" name="submit">Calculate</button>
</form>
</body>
</html>
calculator.js :
//jshint esversion:6
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
//sending response
app.get("/",function(req, res){
res.sendFile(__dirname + "/index.html");
});
//post
app.post("/",function(req,res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1 + num2;
res.send("The result is: "+result);
});
//listen to port 3000
app.listen(3000, function(){
console.log("Server listening on port 3000");
});

In your express server you are expecting the post calls to / and you are telling the form that has to send the form-data to index.html.
That means your form will be sending data to http://localhost:3000/index.html instead of http://localhost:3000/.
You should change action="index.html" to action="/".

Related

Not able to cross beyond my sql statement , the browser waits for something

I am new to node js and js, My code is not able to cross the SQL statement
here is my app.js snippet for the SQL statement
my app.js
//declaration
const bodyParser = require("body-parser")
const fs = require('fs')
const express = require('express')
const app = express()
var session = require('express-session');
const path = require('path')
app.use("/static", express.static('./static/'));
//For the body parser
app.use(bodyParser.urlencoded({extended: false}))
//parse the application Json
app.use(bodyParser.json())
// for the MySQL page
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'login'
})
app.get ('/todo',(req,res)=>{
res.writeHead(200,{'content-type' : 'text/html'})
fs.createReadStream('project1.html').pipe(res)
})
app.listen(process.env.PORT || 3000)
my todo.js
document.addEventListener('submit',myFunction)
function myFunction(e){
console.log("in the data post method")
let sql = 'INSERT INTO `acc` (`name`) VALUES (?)'
connection.query(sql,req.body.name,(error,result)=>{
if(error) throw error
console.log('value inserted')
connection.end();
})
e.preventDefault();
var text = document.querySelector("input").value;
var text = document.querySelector("input").value;
var node = document.createElement("p");
node.id="li1"
if (text!=""){
var textnode=document.createTextNode(text);
node.appendChild(textnode); //append the value to LI
text = document.getElementById("demo")
console.log(text) ;
document.getElementById("demo").appendChild(node); //append the value to UI
document.querySelector("input").value = ""
}
// document.getElementById("demo").addEventListener('mouseover',myFunction1)
str = document.getElementById("li1")
console.log(str)
}
//SELECTING AN ELEMENT THAT WAS CREATAED DYNAMICALLY AND APPLLY SOME PROPERTY
$(document).on('click','p',function(){
$(this).css({"text-decoration": "line-through",color : "pink" });
$(this).fadeOut(1500);
// $(this).remove();
})
my project1.html
<!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>Create a table</title>
<script src="./static/todo.js"></script>
</head>
<body>
<h1>ToDo</h1>
<form id="form" action="/data" method="post">
<input type="text" name = "name" class="input" id="tt">
</form>
<div id= "lip">
<ul id="demo" id="demo">
</ul>
</div>
</body>
</html>
I want to insert the user typed value in the database as well as I have to list them in the front end, both codes work separately but when I combine them, after executing the SQL statement the browser waits for something
Please help me.

getting a 500 error code on post request at a different route

This is a simple bmi calculator and a normal calculator that can add numbers. The html form loads correct to the browser but then once I submit the form, I get a 500 error code on /bmicalculator route alone.
The normal calculator route is working fine ("/").
Error code :
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code:
0.0027180899908172637
at ServerResponse.writeHead (_http_server.js:255:11)
at ServerResponse._implicitHeader (http_server.js:246:8)
at write (_http_outgoing.js:685:9)
at ServerResponse.end (_http_outgoing.js:799:5)
at ServerResponse.send (G:\WebDevelopmentFolder\Calculator\node_modules\express\lib\response.js:221:10)
at G:\WebDevelopmentFolder\Calculator\calculator.js:36:7
at Layer.handle [as handle_request] (G:\WebDevelopmentFolder\Calculator\node_modules\express\lib\router\layer.js:95:5)
at next (G:\WebDevelopmentFolder\Calculator\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (G:\WebDevelopmentFolder\Calculator\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (G:\WebDevelopmentFolder\Calculator\node_modules\express\lib\router\layer.js:95:5)
bmicalculator.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>BMI Calculator</title>
</head>
<body>
<h1>BMI Calculator</h1>
<form action="/bmicalculator" method="post">
<input type="text" name="weight" placeholder="weight">
<input type="text" name="height" placeholder="height">
<button type="submit">Calculate BMI</button>
</form>
</body>
</html>
calculator.js:
//jshint esversion:6
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
//sending response
app.get("/",function(req, res){
res.sendFile(__dirname + "/index.html");
});
//post
app.post("/",function(req,res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1 + num2;
res.send("The result is: "+result);
});
//get
app.get("/bmicalculator",function(req, res){
res.sendFile(__dirname + "/bmicalculator.html");
});
//post
app.post("/bmicalculator",function(req, res){
var weight = parseFloat(req.body.weight);
var height = parseFloat(req.body.height);
var bmi = weight/(height * height);
res.send("Your BMI is: ", bmi);
});
//listen to port 3000
app.listen(3000, function(){
console.log("Server listening on port 3000");
});
do this res.send("Your BMI is: "+ bmi); instead of using , like res.send("Your BMI is: ", bmi);
Because the first params of send() is stand for status code and put content as second parameter.
.send(200, "Your BMI is: "+ bmi)
please rewrite the this as res.send(`Your BMI is: ${bmi}`)
Error in your code
res.send's second argument is the status code and a status code cannot be a float

i am not getting my desired output when i run my node.js code what is the mistake here?

so I've been doin this bmiCalculator where I enter 2 numbers and these 2 numbers are calculated in my server and the answer is displayed but I have been facing troubling in receiving my output.when I click submit i am getting a list of all my files in the index of c but not the answer. Can someone please help me w this?
my HTML code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>BMI calculator</h1>
<form action="/" method="post">
<input type="text" name="num1">
<input type="text" name="num2">
<input type="button" value="submit">
</form>
</body>
</html>
my js code
let express = require("express")
let bodyParser = require("body-parser")
let app = express()
app.use(bodyParser.urlencoded({extended: true}))
app.listen(3000,function(){
console.log("working")
})
app.get('/',function(request,respond){
respond.sendFile(__dirname+"/bmiCalculator.html")
})
app.post('/',function(req,res){
let num1 = Number(req.body.num1)
let num2 = Number(req.body.num2)
let result = num1/num2*num2
res.send(result)
})
According to Express res.send([body]) docs:
The body parameter can be a Buffer object, a String, an object, or an Array
You can't send a number by itself. So you could send a string using result.toString()
You should use <input type="submit" value="submit"> to submit the form.
E.g.
server.js:
let express = require('express');
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(3000, function() {
console.log('working');
});
app.get('/', function(request, respond) {
respond.sendFile(__dirname + '/bmiCalculator.html');
});
app.post('/', function(req, res) {
console.log(req.body);
let num1 = Number(req.body.num1);
let num2 = Number(req.body.num2);
let result = (num1 / num2) * num2;
res.send(result.toString());
});
bmiCalculator.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>BMI calculator</h1>
<form action="/" method="post">
<input type="text" name="num1">
<input type="text" name="num2">
<input type="submit" value="submit">
</form>
</body>
</html>
Server logs after submit the form in client-side:
working
{ num1: '1', num2: '2' }

Quite new to Node JS and I am trying to post to a specific request but it get me error

This is my function to fetch data:
let a = showbtn.addEventListener('click',function(){
list.innerHTML='';
fetch('http://localhost:3000/products')
.then ( response =>response.json())
.then( data => {
data.forEach( product => {
let li =document.createElement('li');
li.textContent=` ${product.id} - ${product.name} - $ ${product.price} `;
list.appendChild(li);
});
})
})
My App.js looks like this:
let express=require('express');
app=express();
//after completing index.html we set index.html as a home page like this by introducing public client folder:
app.use(express.static('public'));
productsArray=[];
//every products must have an id number:
let id=1;
app.use(express.json());
//showing all products:
app.get('/products',(req,res)=>{
res.send(productsArray);
})
//creating ptoducts(posts):
app.post('/products',(req,res)=>{
let newProduct=req.body;
newProduct.id=id;
id++;
productsArray.push(newProduct);
res.send('new product created by newProduct=req.body and added to array by push method: Array.push(newProduct)')
})
This is my HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>shop</title>
</head>
<body>
<h1>shop</h1>
<h2>show all products</h2>
<button class="show-products">show</button>
<!-- //everyl ist item is a separate product -->
<ul class="product-list"></ul>
<!-- //.................................................................... -->
<h2>add product</h2>
<form class="add-product-form">
<p>
<label for="add-product-name">
product:
</label>
<input id="add-product-name" type="text" >
</p>
<p>
<label for="add-product-price">
price:
</label>
<input id="add-product-price" type="text" >
</p>
<button>add</button>
</form>
<script src="js/script.js"></script>
</body>
</html>
The problem is that when i open chrome on localhost:3000 and type something in the field of products and price after that i click show button but i get this result something like this:
1 - undefined - $ undefined
the first one is it's id and the second is product name but is undefined and price as well. I think something is wrong with value but i can't solve this problem.
Thank you in advance.
When handling POST bodies in express you need to user body-parser
http://expressjs.com/en/resources/middleware/body-parser.html
npm install body-parser
var bodyParser = require('body-parser')
Code from the docs
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
in the js file remove the semicolon and replace it with comma

node.js: How can I output a variable directly to index.html

How can I get the user inputs from index.html, process in node and output the result back into the index.html? Instead of outputting - as currently does - to a new page.
Form file
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile('index.html', { root: __dirname});
app.post('/mess', function(req, res){ //means same dir
var userNum1 = req.body.num1;
var userNum2 = req.body.num1;
var answer = parseInt (userNum1) + parseInt (userNum2);
res.send ('The answer is ' + answer);
});
app.listen(80);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Forms></title>
</head>
<body>
<form action="mess" method="post">
<p>Enter a number:</p>
<input type="text" name="num1" placeholder="..." />
<br>
<p>Enter a number:</p>
<input type="text" name="num2" placeholder="..." />
<br>
<button type="submit">Submit</button>
<br>
</form>
</body>
</html>
Probably the easiest way is to use ejs.
First npm install ejs. Then add this to your Express app code:
app.set('view engine', 'ejs');
// this allows you to render .html files as templates in addition to .ejs
app.engine('html', require('ejs').renderFile);
In your route handler you just do something like:
res.render('form', { answer: 'foo' });
and then your template (e.g. ./views/form.html) would look like:
<html>
<p> The answer is <%= answer %> </p>
</html>
An alternative to the EJS is to use socket.io. You can attach an event handler to each entry, or to the submit button and then use socket.io to send it from client to server, process it and have it sent back. Then you page can update on receiving the data from the server.

Categories