How to sens and access parameters with POST method - javascript

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.

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.

vue + nuxt.js - How to read POST request parameters received from an external request

I have a an external form which submits a post request to my nuxt app. I am struggling currently to find out how I can access these POST request parameters in my nuxt page?
I found so far the "asyncData" method, but when I try to access the submitted parameter through the "params" object it is always "undefined". What do I wrong here?
"asyncData" nuxt reference
example code in my nuxt page, assuming "email" is the request parameter submitted from outside
export default {
asyncData({ params }) {
console.log('asyncData called...' + params.email);
return {email: params.email};
},
external html form
<body>
<form action="https://..." target="_blank" method="post">
<input name="email" class="input" type="text" placeholder="Email" maxlength="255"></input>
<input name="submit" class="btn" type="submit" value="Ok"></input>
</form>
</bod>
I found a way, as described in "asyncData" nuxt reference you can pass the request and response object to the "asyncData({req,res})" call.
Here an example - assuming 'email' is one of the post parameter. querystring is a module of node.js and allows you to parse the request body into an array.
Small Remark - this seems only to work for nuxt page level components but not for lower level components
<script>
export default {
asyncData({ req, res }) {
if (process.server) {
const qs = require('querystring');
var body = '';
var temp = '';
while(temp = req.read()) {
body += temp;
}
var post = qs.parse(body);
return {data: post};
}
},
data() {
return {
data: '',
}
},
mounted() {
console.log(this.data['email']);
},
</script>
Nuxt.js cannot handle such things by itself.
https://nuxtjs.org/api/configuration-servermiddleware
You should implement your own middleware for such cases.
And asyncData has nothing to do with handling inbound POST data.

How to submit form data using restify and post?

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?

CherryPy and CORS

I have an nginx server set up where I would like to set up a service that receives a string and returns a result. I plan to use Python to do the processing, with CherryPy as an interface. I've tested the CherryPy part, and know it receives properly. When I try to connect to the CherryPy service with a web page, I get CORS errors. How can I get them to communicate?
Here's the Python Code:
import cherrypy
import random
import urllib
class DataView(object):
exposed = True
#cherrypy.tools.accept(media='application/json')
def GET(self):
rawData = cherrypy.request.body.read(int(cherrypy.request.headers['Content-Length']))
b = json.loads(rawData)
return json.dumps({'x': 4, 'c': b})
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == '__main__':
conf = {
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True,
}
}
cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
cherrypy.config.update({'server.socket_port': 3000})
cherrypy.quickstart(DataView(), '', conf)
Here's my web page:
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script type="text/javascript">
$(document).on('click', "#submitButton", function(){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
contentType: 'text/plain',
xhrFields: {
// The 'xhrFields' property sets additional fields on the XMLHttpRequest.
// This can be used to set the 'withCredentials' property.
// Set the value to 'true' if you'd like to pass cookies to the server.
// If this is enabled, your server must respond with the header
// 'Access-Control-Allow-Credentials: true'.
withCredentials: false
},
headers: {
},
success: function() {
console.log("Success");
},
error: function() {
console.log("Fail");
}
});
});
</script>
</head>
<body>
<div id="header">
<h2>PDE Grammar Engine</h2>
<form>
Input Sentence:<br>
<input type="text" name="query" id="query"><br>
<input type="submit" id="submitButton" value="Submit">
</form>
</div>
</div id="results">
</div>
</body>
</html>
Turned out that the CherryPy server was not actually listening to the correct address. It was allowing connections from localhost, but not external connections. I had to add the following entry to the cherrypy.config.update
cherrypy.config.update({'server.socket_host': '0.0.0.0',
'server.socket_port': 3000})

Cannot read post parameters from req.body in Express.js 4.13.x

Objective: I'm new to Node.js and Express.js framework. Currently I'm writing a small app using IONIC framework where I trying to pass user basic details like FirstName, LastName to node.js server as a matter of first step. Then once I read the data I'm planning to save the data in the database.
Issue: Currently when I pass the details (in this case just FirstName for testing purpose) through POST request from my app to the node js server and when i try to access the FirstName using req.body.FirstName, the server returns "undefined".However when I use console.log(req.body) it returns the value for eg., { '{"FirstName":"test"}': '' }.
I'm not sure where did I miss. I suppose I referred a lot of links thru Google, nothing seems to be working out. It might be a simple thing, but it is bothering me lot and I'm wasting time to find the solution.
Configuration:
Express.js - 4.13.3
I've tried different combination based on the related links for this issue. Nothing seems to be working. Any guidance or advise will be really helpful as I got struck in this.
serverapp.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,POST');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post('/', function(req, res) {
console.log("Hi from server", req.body);
console.log("Hi this is key value", req.body.FirstName); // this throws error as undefined
});
var server = app.listen(8100, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Code snippet from Controllers.js - Post request is sent via this.
var url = 'http://localhost:8100'
var request = $http.post(url,
{'FirstName': $scope.Model.FName}, {headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}});
Rego.html file
<form name="tab-Registration.form">
<div class="list" align="left">
<label class="all_page_bgColor" align="left">
<input type="text" name="FName" placeholder="First Name" ng-model="Model.FName" class="all_page_bgColor" align="left">
</label>
<label class="all_page_bgColor" align="left">
<input type="text" name="LName" placeholder="Last Name" ng-model="Model.LName" class="all_page_bgColor" align="left">
</label>
<label class="all_page_bgColor" align="left"> <!-- class="item item-input" -->
<input type="text" name="Email" placeholder="Email" ng-model="Model.Email" class="all_page_bgColor" align="left">
</label>
<label class="all_page_bgColor" align="left">
<input type="text" name="PhoneNo" placeholder="Phone" ng-model="Model.PhoneNo" class="all_page_bgColor" align="left">
</label>
</div>
<div align = "center">
<button class="button button-assertive" ng-click="submit()">Submit</button>
</div>
</form>
This object { '{"FirstName":"test"}': '' } has only one key which is {"FirstName":"test"} and the value is empty string. Actually the whole object is the key of first value.
Object must be like this: {"FirstName":"test"}
But i don't know how things end up like this. You have FName in your form but you get this, and I don't know what this IONIC framework is and how it works. I think it's better to start with experimenting with express.js then switch to higher level frameworks.
I've resolved this. The solution is to use transformRequest while sending the request to the server for URL encoded data, coz the request send to server by default sends Json object. And when you want to over-ride that, you have to use transformRequest
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
FirstName: $scope.Model.FName}

Categories

Resources