this is form example in html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="/myaction" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
and this is node.js function that run on the server:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
switch (req.url)
case '/myaction':
res.end(?????);
break;
}
}).listen(8080);
sys.puts('Server running at http://127.0.0.1:8080/');
I have 2 questions:
How can I call myaction function in the node.js from the html page? Because the html file runs on port 80 and node.js on 8080 (when I try to move the node.js to port 80 it writes "// Unhandled 'error' event")
In the node.js function where I put "?????" how can I get data from the html form.
When I type req.html.body.name I don't get the data...
Using http.createServer is very low-level and really not useful for creating web applications as-is.
A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.
When you have, you can create a basic application to handle your form:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
You can make your form point to it using:
<form action="http://127.0.0.1:8080/myaction" method="post">
The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.
I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.
If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.
It might help to look at this answer, which is very similar to your quest.
Related
to demonstrate what im trying to do using a simple example:
<html>
<head>
<base target="_top">
</head>
<body>
<form id="uploaderForm" action="https://script.google.com/macros/.......exec Method="POST">
<input type="text" name="applicantName" id="applicantName">
<input type="text" name="applicantEmail" id="applicantEmail">
<input type="button" value="Submit">
</form>
<script>
.
.
.
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
</script>
so this is an example of the html and js page that is in my pc, not in the google app, i just called the google app in the form, and in the javascript part im calling a function called uploadFile, which is located in the google script, but obviously i get an error in the console , it says :
Uncaught ReferenceError: google is not defined
at uploadFiles (6166bff606ac6fee1994e592:67)
at HTMLInputElement.onclick
is it possible to call a GAS function inside JS that is not in the GAS html.
is what im trying to do even possible, the whoel reason im doing this is so that i can pass the username and email automatically from the database to the app, the app works if the html part is hosted in the google app script, but then i cant figure out how to pass the email and username to it because in this case i call the app using , so is it possible to pass the username and email through the iframe call, i dunno im very new to this i have so many questions, honestly the documentation wasn't helpful to me. please feel free to comment anything, everythign is helpful
Since you're just posting the form data, you can name the function you want to call as doPost()(instead of uploadFile) and it will receive the posted data. You have to republish the webapp as a new version after the modification.
I just ran it as a dialog. I returned the data back into the success handler and loaded by into the html to insure it was working.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<body>
<form>
<input type="text" name="applicantName" id="applicantName"/>
<input type="text" name="applicantEmail" id="applicantEmail"/>
<input type="button" value="Submit" onclick="uploadfile(this.parentNode);" />
</form>
<div id="msg"></div>
<script>
function uploadfile(form) {
google.script.run
.withSuccessHandler((m) => document.getElementById("msg").innerHTML = m)
.uploadMyFile(form);
}
</script>
</body>
</html>
gs:
function uploadMyFile(obj) {
return `Applicant Name: ${obj.applicantName}<br />Applicant Email: ${obj.applicantEmail}`;
}
function launchFormDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah2'),'Test Dialog');
}
Dialog:
I'm frustrated because I can't send from HTML or receive from Node.js JSON data. I think that I'm near to resolve, but I'm tired trying for hours. Anybody helps me?
As the code below, the responde is null (req.body = null?) in my VSCODE.
When I try from Insomnia, that's ok. When I try from HTML Form, fails. *
I could to use BodyParser, but why to send from Insomnia works and from HTML Form doesn't?
//routes.js
routes.post('/go', (req, res) => {
console.log(req.body)
return res.json({ "Response": req.body })
})
<!DOCTYPE html>
<html>
<head>
<title>API Correios</title>
</head>
<body>
<form id="FrmQuery" action="http://localhost:3333/go" method="POST" enctype="application/json">
<label for="sCepOrigem">Cep Origem</label><br>
<input type="text" name="sCepOrigem" id="sCepOrigem"><br><br><br>
<input type="text" id="jsonData"><br><br>
<button id="send" type="button">Enviar</button>
</form>
<script>
document.querySelector('#send').addEventListener('click', (event) => {
let sCepOrigem = document.querySelector('#sCepOrigem')
var obj = {
"sCepOrigem": sCepOrigem.value,
};
var myJSON = JSON.stringify(obj);
document.querySelector('#jsonData').value = myJSON
document.querySelector('#FrmQuery').submit()
})
</script>
</body>
</html>
In Javascript from web browser you need to send it as raw XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Other possibilities would be jQuery's $.ajax or maybe the new fetch API.
Based on my experience with node js, I believe you have to simply res.send and cut out the return statement.
Hope this helps.
I want to use form input from HTML to JS. For that i am using following snippet but getting "SyntaxError: Unexpected token if" can anyone help in modifying it.
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function(req, res) {
fs.readFile(html_form_path, function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
var q = url.parse(req.url, true);
var qdata = q.query;
res.write(qdata.Input());
}).listen(8080);
HTML FORM:
<html>
<body>
<form type='get'>
<input type="text" name='Input'>
<input type='submit'>
</form>
</body>
</html>
You should send data from html to server, you will need bodyparser and it is easiest to do if you also have express on server then you make submit button and i form tag add action and method atributes and on server you expect
app.post("/action",function(req,res){
req.body.input
})
html:
<form action='/action' method='POST' >
<input name=input''>
<input type='submit'>
</form>
also this will reload your page, if you want not to reload you need use ajax to send data you can use axios in javascript.
see express docs on how to set it up and you need see bodyparser docs and then use this code
I'm trying to learn express. I'm using FS to load my HTML Page. The only thing I could find on this with a google search was using ASP.NET instead of Express.
Server.js:
var express = require('express');
var path = require('path');
var fs = require('fs');
var app = express();
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname+'/')))
app.get('/', function(a,b,c){
fs.readFileSync('index.html');
});
app.post('/testaction', function(a,b){
console.log(a.body.log);
fs.readFileSync('Logged.html');
});
app.listen(3000);
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<form method="post" action="http://localhost:3000/testaction">
<h1>Log This:</h1>
<input type="text" name="log"/>
<input type="submit", value="Press Me!"/>
</form>
</body>
</html>
In order to serve files you don't have to use fs. Example:
app.get('/', function(req, res, next) {
res.render('index');
});
If you need to redirect, you can use:
res.redirect('/staticFile.html');
Remove these lines:
app.get('/', function(a,b,c){
fs.readFileSync('index.html');
});
This line is middleware and it applies to all routes on every request:
app.use(express.static(path.join(__dirname+'/')))
It's purpose is to serve static files from whatever path you provide. In this case you're serving from the root directory so you can navigate to all your code files like http://localhost:3000/package.json for example.
It applies to all HTTP methods, get post put etc...
When you write app.get('/' you override that middleware with a new route and try serving only one file. Just drop that code and you'll server everything statically from the directory you specified above.
If you don't want to serve your code files, put your static files in a different folder such as "site" and set your static path to that folder, for example:
app.use('/', express.static(__dirname + '/site'));
I'm an absolute newbie in angularjs and don't have any idea about web services either.
My requirement is something like this:
I'll have a basic login page (to be designed using html and angularjs) which is going to ask for my credentials (Username and Password). On providing a set of credentials and clicking on the "Submit" button, my code needs to process the form data and pass the information on to a webservice. I just have the url of the webservice with me and nothing else.
Thus my principal objective would be to send across the username and password to the webservice (preferably as a JSON object) and check whether its working properly or not. So far, I've successfully managed to:
1> Hit the webservice (I've used $resource for doing the same.)
2> Store the username and password as a JSON object.
Now I need to accomplish two things:
1> send this data as "POST" and most importantly, 2> send this JSON data(as an object or string) to the webservice.
I'm absolutely clueless...Please help me out by modifying my code.
Thanks in advance. Here's my JS file:
var app = angular.module('angularjs-starter', ['ngResource']);
app.controller('MainCtrl', function ($scope,$http,$resource) {
$http.defaults.useXDomain = true;
$scope.checkUsername = function(){
var USERNAME = $scope.inputUsername;
var PASSWORD = $scope.inputPassword;
var f = JSON.stringify({USERNAME: USERNAME, PASSWORD: PASSWORD });
var result= JSON.parse(f);
var Something = $resource("/some url/:id", {id: "#id"},
{
post:{
method:"POST",
isArray:false
},
});
$scope.something = Something.get({id:1});
$scope.alertMessage = "Web service has been successfully hit!";
};
});
And here's my HTML file:
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Authentication</title>
<script src="C:\Users\Rup\Desktop\POC2\js\angular.js"></script>
<script src="C:\Users\Rup\Desktop\POC2\js\angular-resource.js"></script>
<script src="C:\Users\Rup\Desktop\POC2\experiment_2.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="MainCtrl">
<h1>Hello</h1>
<form name="form1" class="form-horizontal">
<label class="control-label" for="inputUsername">Username</label> <input
type="text" id="inputUsername" placeholder="Username"
ng-model="inputUsername"> <br /> <label
class="control-label" for="inputPassword">Password</label> <input
type="password" id="inputPassword" placeholder="Password"
ng-model="inputPassword"> <br /> <span class="help-block">{{alertMessage}}</span>
<br />
<!--<a class="btn">Sign in</a>-->
<button ng-click="checkUsername()">Submit</button>
</form>
</body>
</html>
The good news is that this should be fairly straight forward. You have the right idea, you just need to extend the resource object as you have done with "post" method, and when you call it - pass in your JSON object. Angular will then append the passed in JSON object as post parameters automatically. It's a good idea (I've read), to create this User resource as a service/factory so that you can inject it into your controllers to abstract the calls to the server. As an example - something I have done would be to create the service like so (with a dependency on the angular $resource):
var myApp = angualar.module('myApp', []);
myApp.factory('UserService', ["$resource",
function UserService($resource) {
var UserService = $resource('/rest/user', {}, {
search: {
method: 'POST',
url: window.location.origin +'/yourServer/rest/search' //custom url of your service to be called
}
});
return UserService;
}
])
Then in your controller, you inject the service to be used, and create a method that then calls your shiny new service:
myApp.controller("myAppController", ["$scope", "UserService",
function myAppCtrl($scope, UserService) {
$scope.search = function () {
var params = {
param1: "searchValue1",
param2: "searchValue2"
}
var response = UserService.search(params);
response.$promise.then(
function success() {
//celebrate!
},
function fail(err) {
//comiserate
}
);
}
}
The response object from the call to the service method is a promise, which you attach your success or fail functions to be called when the call successfully returns or fails.