How to submit form data using restify and post? - javascript

I want to print an input value using restify and post route, but it's not working. The form.html page opens and upon submitting, I see this in URL:
http://localhost:8081/?name=dsf
But I don't see any message in console. Am I doing something wrong?
Here's my code:
select.js
var restify=require('restify');
var server=restify.createServer();
var mysql=require('mysql');
server.listen(8081, function(){
console.log("%s is running at %s", server.name, server.url);
});
var pool=mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'books'
});
server.get(/\/?.*/, restify.serveStatic({
directory: __dirname,
default: 'form.html'
}));
server.post('/hello/', function send(req, res, next){
pool.getConnection(function(err, connection){
if(err){
}else{
var table=req.body.name;
console.log(table);
}
});
});
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST">
<input type="text" name="name">
<input type="submit" value="submit">
</form>
</body>
</html>
Both files are in C:/restify folder.

action attribute is missing in your <form> tag. Try to set it to action="/hello/". Does it solve your problem?

Related

Using Firebase with Express: app.post() not working with existing files under the public folder

I am currently learning express.js and building a dynamic website with firebase. The website is really simple, it takes two numbers from user input and sends back the sum. I have one test.html in the public folder, which contains the html form, inputs, and submit button. In index.js in the functions folder I specified the app.post method, and in firebase.json in my project folder the rewrite properties is the same as the tutorial from firebase: Use a web framework.
/public/test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Calculator</h1>
<form action="/test" method="post">
<input type="text" name="num1" placeholder="Enter your first number">
<input type="text" name="num2" placeholder="Enter your second number">
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
/functions/index.js:
const functions = require("firebase-functions");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/test", (req, res) => {
res.send("The answer is " + (Number(req.body.num1) + Number(req.body.num2)));
});
exports.app = functions.https.onRequest(app);
/firebase.json:
{
"hosting": {
"public": "public",
......
"rewrites": [ {
"source": "**",
"function": "app"
} ]
}
......
}
When I open the page, the form, boxes, and submit button appear just as specified in the test.html file. I expect that when I enter two numbers in the input boxes the website would return their sum, as specified in index.js. However, when I click the submit button, nothing happens.

i am trying to render an ejs file and the page keeps loading for hours

app.get('/all-datas', (req, res) => {
data.find({}, function (err, names) {
res.render('EJS.ejs', {
nameList: Uname
})
})
})
I want this code to be used in my javaScript but when http://localhost:5000/all-datas is accessed this the page does not render and keeps loading and loading
or just tell me the any other way
I have installed all required modules
tried changing the port
done lots and lots changes still i cant help
I also had the same problem. The cause of the problem in my case was that I was not redirecting when handling post request.
app.js
const express=require("express")
const bodyparser=require("body-parser")
const path=require("path")
const app=express()
app.set("view engine", "ejs")
app.set("views", path.join(__dirname, "views"))
app.use(bodyparser.urlencoded({extended:true}))
const list=[]
app.get("/", (req, res)=>{
const day=new Date()
const options={
weekday:"long",
day:"numeric",
month:"long"
}
const today=day.toLocaleDateString("en-US", options)
res.render("list.ejs", {day:today, list:list})
})
app.post("/", (req, res)=>{
const task=req.body.newItem
list.push(task)
res.redirect("/")
})
app.listen(3000)
list.ejs
<!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>Document</title>
</head>
<body>
<h1><%=day%></h1>
<h2>To Do List</h2>
<ul style="list-style-type: none; margin:0; padding: 0;">
<%for(let i=0; i<list.length; i++){%>
<li><%=list[i]%></li>
<%}%>
</ul>
<form action="/" method="post">
<input type="text" name="newItem">
<input type="submit" value="Add">
</form>
</body>
</html>
First of all, you don't need to specify the extension on '.ejs' on render. you are also not using the 'names" parameter inside the callback function. if you want to take 'Uname' from 'names'( Output docs of the query ), you can pass the whole array to ejs and take "uname" from there by using a loop (ex: forEach Loop).
To render all usernames form the Namelist
app.get('/all-datas', (req, res) => {
data.find({}, function (err, names) {
res.render('EJS', {
nameList: names
})
})
})
on Ejs :
<% nameList.ForEach((item)=>{ %>
<p> username: <%= item.Uname %> </p>
<% }) %>
If This doesn't work, Make sure you have written the loop on the Ejs file correctly.

How can I pull a JS variable into EJS theme page?

This is the variable on the index.js: /* a unique referral code the user can share */ let referral_code = shortid.generate();
I just want to the pull it onto the index.ejs page like $({referrer_code}) or whatever would be appropriate to then get the variable from the index.js page. I'm just having trouble with the simple task of passing the referrer_code variable into the express web page template.
A bit new to React and js and could use some guidance.
Please help me pull my basic js variable into the ejs express theme page.
All I want to do is take the variable called referral_code and place it on the page as visible html text.
The variable I'm trying to display directly in html form on the theme can be seen on the index.js page, where it says:
"let referral_code = shortid.generate();"
Here's the full index page:
var router = express.Router();
var mysql = require('mysql');
var shortid = require('shortid');
/* New POST route for form submissions */
router.post('/', function(req, res, next) {
/* establish mysql connection */
var connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
/* user's email address */
let email = req.body.email;
/* a unique referral code the user can share */
let referral_code = shortid.generate();
/* the referral code a user submitted (might be null) */
let referrer = req.body.referrer;
/* add user to the database with INSERT */
let query = "INSERT INTO `users` (`email`, `referral_code`, `referrer`) VALUES (?, ?, ?)";
connection.query(query, [email, referral_code, referrer], (err, rows) => {
connection.end(function() {
if (err) return next();
return res.send({referralCode: referral_code});
});
});
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
Here's the theme page I'm trying to update. You can see in the code where I added: {referral_code} and that is where I wnat to display the referral_code.
<!DOCTYPE html>
<html>
<head>
<title>The Starseeds Referral App</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
<h1>SignUp to Earn Your Free Tokens!</h1>
<input type="email" id="email" placeholder="Enter your email...">
<input type="text" id=" as" placeholder="Referral code">
<button id="submit">Sign up</button>
<script>
$('#submit').on('click', function(e) {
e.preventDefault();
$.ajax({
url: '/',
type: "POST",
data: {
'email': $('#email').val(),
'referrer': $('#387jh6g').val()
},
"newAffiliate" = res.referralCode,
success: function(res) {
alert('Your referral code is: ' + res.referralCode);
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
})
</script>
<H2>
<label>Your referral code: </label>
<span id='newAffiliate'>
{referral_code}
</span>
</H2>
<p>
(Be sure to enter your friend's referral code so you both can get tokens.)
</body>
</html>
Would also like to append url to the beggining of the code, but I'm assuming that is standard?
Thanks for taking a look to help me solve this!

having trouble in passing req data in post fumction through html form in node js

I am newbie to nodejs. Facing problem in posting data throug html forms....
In my server.js i have added this post function request
app.get('/',(req,res)=>{
res.end(`
<!doctype html>
<html>
<body>
<form action="/product" method="post" role="form" enctype="multipart/form-data">
<input type="text" id="title" name="title" placeholder="title">
<input type="number" name="price" placeholder="price">
<input type="text" name="description" placeholder="description">
<input type="text" name="category" placeholder="category" >
<input type="file" name="product" >
<button>Save</button>
</form>
</body>
</html>
`);
})
Post function decleration in product.js
const productRouter = express.Router();
productRouter.use(bodyParser.json());
productRouter.route('/')
.get((req,res,next)=>{
Product.find({})
.then((products)=>{
res.statusCode=200;
res.setHeader('Content-Type','application/json');
res.json(products);
},(err)=>next(err))
.catch((err) => next (err));
})
.post((req,res,next)=>{
console.log(req.body);
var Prod= new Product({
title:req.body.title,
price:req.body.price ,
description: req.body.description,
category:req.body.category,
img: req.body.img
});
Prod.save()
.then((product)=>{
console.log('product added ',product );
res.statusCode=200;
res.setHeader('Content-Type','application/json');
res.json(product);
},(err)=> next(err))
.catch((err) => next(err));
})
Post request in working fine when i am doing it using POSTMAN , but when try to do using html form i am facing the follwing error:
ValidationError: Product validation failed: title: Path title is required., price: Path price is required., description: Path description is required., category: Path category is required., img: Path img is required.
at model.Document.invalidate (C:\Users\mayank\Desktop\cata\node_modules\mongoose\lib\document.js:2598:32)
Check the notes from body-parser README section (attached screenshot for reference). BodyParser doesn't support the multipart styles due to their complexity. Instead, listed some nm-modules to use.
I suggest MULTER or MILTIPARTY
Here's a reference of the code that's working.I have sent the received-payload as JSON response. You could go ahead and process the way, you intend.
router.post('/ola', (req, res) => {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
res.json({ fields: fields, files: files });
});
})

How to sens and access parameters with POST method

I'm creating an authent form for my web page with Javascript and using Vue JS on client side and NodeJS with ExpressJS on server side.
On server side I writed my post method :
server.app.post("/login", function(req, res) {
console.log(req.body.username);
})
On client side, I have my form on my html link to a Vue instance:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="authent">
<p>Username :</p>
<input type="text" name="username" v-model="username" required>
<p>Pwd :</p>
<input type="password" name="password" v-model="password" required>
<button v-on:click="authent">Login</button>
</div>
<script src='/authent/vue.js'></script>
<script src='/authent/vue-resource.min.js'></script>
<script src="authent.js"></script>
</body>
</html>
window.onload = function () {
var authent = new Vue({
el: '#authent',
data: {
username: null,
password: null
},
methods: {
authent: function() {
try {
this.$http.post('/login', {"username": authent.username, "password": authent.password})
.then(function(response) {
console.log(response.body);
})
} catch (e) {
console.log(e);
}
}
}
})
}
Apparently I wrongly send parameters in vue instance because on server side the req.body is undefined.
EDIT
Parameters are sent, but I don't know how I can access them in my post method on server side.
you send it through ajax way. and you probably also send it as json object not a real post data. in express you should write (to have a json parser)
app.use(express.json());
and just to be safe. add a body parser too :-)
app.use(express.urlencoded({ extended: true }))
you probably will need it too sooner or latter
just add the above middlewares
I'm not familiar with Vue, but can you try to use this.username instead of authent.username ?
In your devTools, can you see that params has been seend ? To be sure that's a front-end issue.

Categories

Resources