Node.js/Express form post req.body not working - post

I'm using express and having trouble getting form data from the bodyParser. No matter what I do it always comes up as an empty object. Here is my express generated app.js code (the only thing I added was the app.post route at the bottom):
var express = require('express');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
res.sendfile('./public/index.html');
});
app.post('/', function(req, res){
console.log(req.body);
res.sendfile('./public/index.html');
});
app.listen(3010);
Here is my HTML form:
<!doctype html>
<html>
<body>
<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
</body>
</html>
When I submit the form, req.body is an empty object {}
Its worth noting that this happens even if I remove the enctype attribute from the form tag
...Is there something I am missing/doing wrong?
I am using node v0.4.11 and express v2.4.6

<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="I_appear_in_req_body" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
The body of a HTTP post is a key/value hash of all the form controls with a name attribute, and the value is the value of the control.
You need to give names to all your inputs.

It also due to content type. please see console.log(req) object.
'content-type': 'application/json; charset=UTF-8’ // valid.
'content-type': 'application/JSON; charset=UTF-8’ // invalid & req.body would empty object {}.
To check content type by console.log(req.is('json')) // return true/false
I think 'charset=UTF-8' is negligible in above.

If your form looks like this
<form action="/", method="post">
<label for="for_name">Name: </label>
<input id="for_name" type="text" name="user_name"/>
<button type="submit">Submit</button>
</form>
And if you are using the following line of code
app.use(express.json());
then the req.body will be empty because it only parses req with content-type application/json but the default value of request originating from element is application/x-www-form-urlencoded. Hence the following line of code will solve the issue
app.use(express.urlencoded({ extended: true }));
My first StackOverflow contribution. Yay!!

Related

angular2 material - md-error and username does not exists from a server call

This is my login form. If a user puts in a wrong username and does not exists on the server then how do I use md-error to display message?
E.g.
Here is the json I get back for auth from a submit:
{is_username: false, status: false}
Here is how I set up my form:
this.myForm = fb.group({
username: ['',[Validators.required]],
password: ['',[Validators.required]]
})
Here is my HTML:
<md-input-container>
<input mdInput type="email" placeholder="Username" [(ngModel)]="username" formControlName="username" style="width: 300px;outline: none;">
<md-error *ngIf="myForm.get('username').hasError('required')">Username is required</md-error>
<md-error *ngIf="myForm.get('username').hasError('username_exists')">Username does exist</md-error>
</md-input-container>
So..how do I trigger a md-error message if is_username is false?
I've been doing server side validation like this.
<md-input-container>
<input mdInput type="email" placeholder="Username" [(ngModel)]="username" formControlName="username" style="width: 300px;outline: none;">
<md-error *ngIf="myForm.get('username').hasError('required')">Username is required</md-error>
<md-error *ngIf="myForm.controls['username'].hasError('username_exists')">{{myForm.controls['username'].errors['username_exists']}}</md-error>
</md-input-container>
Then, set the error after you get the response from the server.
https://angular.io/api/forms/AbstractControl#setErrors
this.myForm.controls['username'].setErrors({
'username_exists': 'Username does exist'
});
I typically return validation error messages from the server as well, which could be used here.

Using the Grails Stripe plugin

I'm using Stripe grails plugin in my application and I'm getting the below error:
Class:groovy.lang.MissingPropertyExceptionMessage:No such property: Stripe for class: com.myApp.app.SubscriptionRequestController
Here is my action:
def charge(String stripeToken, Double amount) {
Stripe.apiKey = grailsApplication.config.grails.plugins.stripe.secretKey
def amountInCents = (amount * 100) as Integer
def chargeParams = [
'amount': amountInCents,
'currency': 'usd',
'card': stripeToken,
'description': 'customer#sample.org'
]
def status
try {
Charge.create(chargeParams)
status = 'Your purchase was successful.'
} catch(CardException) {
status = 'There was an error processing your credit card.'
}
redirect(action: "confirmation", params: [msg: status])
return
}
i'm also getting the below error since i installed the plugin when i remove it i don't see it, it occurs while trying to access or refresh any view :
java.lang.RuntimeException: It looks like you are missing some calls to the r:layoutResources tag. After rendering your page the following have not been rendered: [head]
Try this:
in your main layout file e.g.: main.gsp, have the two additional both in body and head. Also, loads the stripe-v2 manually. No need to add it in web-app/js as the plugin itself already has it.
<html>
<head>
<g:javascript src="stripe-v2.js" />
<r:layoutResources/>
</head>
<body>
<g:layoutBody/>
<r:layoutResources/>
</body>
</html>
in config.groovy add:
grails.resources.modules = {
stripe {
dependsOn 'jquery'
resource url:'/js/stripe-v2.js', disposition: 'head', exclude:'minify'
}
}
Sample gsp (taken from the docs) but i added payment-errors as the source use it:
<stripe:script formName="payment-form"/>
<g:form controller="checkout" action="charge" method="POST" name="payment-form">
<div class="payment-errors"></div>
<div class="form-row">
<label>Amount (USD)</label>
<input type="text" size="20" autocomplete="off" id="amount" name="amount"/>
</div>
<stripe:creditCardInputs cssClass="form-row"/>
<button type="submit">Submit Payment</button>
</g:form>
I think the plugin itself did not support the current implementation of Grails Asset Pipeline.I think it is not compatible for grails 2.4.3 and above.
As it stands, you probably aren't importing the com.stripe.Stripe class which is why you're getting that particular message.
You don't need to attempt to manually assign the secret key to the Stripe class. Just define grails.plugins.stripe.secretKey in your Config.groovy and the plugin will handle the rest, as you can see in the plugin source.

j_spring_security_check redirect

I upgraded my application from 2.2.3 to 2.4.3. Now when I click submit on the login page, I see that the POST request to j_spring_security_check has status code 302.
Is there something I need to do after upgrading? I've tried running grails clean-all but that did not help.
I'm using this version: compile ':spring-security-core:2.0-RC3'
settings in config.groovy
grails.plugins.springsecurity.userLookup.userDomainClassName = 'com.aerstone.scanner.security.User'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'com.aerstone.scanner.security.UserRole'
grails.plugins.springsecurity.authority.className = 'com.aerstone.scanner.security.Role'
GSP
<form action="${postUrl}" method="POST" id="loginForm" autocomplete="off">
<input type='text' name='j_username' id='username' placeholder="Username"/>
<input type='password' name='j_password' id='password' placeholder="Password"/>
<input type="submit" class="btn" value="Sign in" id="submit"/>
</form>
I had the same issue after an upgrade.
I changed the action of the login form by:
<form action='${ request.contextPath }/j_spring_security_check' method="POST">
Hope that helps
please note that the name had change in the config to be:
grails.plugin.springsecurity....
Notice 'plugin' vs 'plugins'. I've passed this problem but I'm getting invalid credentials all the time.

phpCAS::isAuthenticated returning false after login in different service

I've configured the CAS login page so that it accepts the username and password as GET parameters and if these are provided, it submits the login form automatically. This looks as the CAS login page is not even touched during authentication from the website.
The website is using phpCAS version 1.3.2 to communicate with CAS. If I log in directly through the form, It works as expected: the browser gets redirected back from CAS correctly and isAuthenticated() returns true. However if I log in to a different service beforehand, isAuthenticated() returns false. If I'm not mistaken this is because I have to do an actual check with CAS if the auth is fine, therefore I've also tried checkAuthentication(), but I get the following errors:
[error] [client 192.168.12.120] PHP Fatal error: Uncaught exception 'CAS_AuthenticationException' in /home/dev/www/CAS-1.3.2/CAS/Client.php:2248
Stack trace:
#0 /home/dev/www/CAS-1.3.2/CAS/Client.php(1227): CAS_Client->_validatePGT('https://192.168...', '????<cas:servic...', Object(DOMElement))
#1 /home/dev/www/CAS-1.3.2/CAS/Client.php(1131): CAS_Client->isAuthenticated()
#2 /home/dev/www/CAS-1.3.2/CAS.php(1078): CAS_Client->checkAuthentication()
#3 /home/dev/www/redir.php(39): phpCAS::checkAuthentication()
#4 {main}
thrown in /home/dev/www/CAS-1.3.2/CAS/Client.php on line 2248, referer: https://192.168.10.144:8181/cas/login?username=myUser&password=testpassword&auto=true&service=https%3A%2F%2F192.168.12.120%2Fredir.php
CAS server log
phpCAS debug log
PHP Code:
<?php
function pageURL() {
$PROTOCOL = "http";
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$PROTOCOL = "https";
}
$url = "$PROTOCOL://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url = strtok($url, '?');
return $url;
}
// Configuration
$phpcas_path = "CAS-1.3.2";
$cas_host = "192.168.10.144";
$cas_port = 8181;
$cas_context = "/cas";
// Load the CAS lib
require_once $phpcas_path . "/CAS.php";
// Enable debugging
phpCAS::setDebug ();
// Initialize phpCAS
phpCAS::proxy ( CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context );
phpCAS::setNoCasServerValidation ();
// check CAS authentication
$auth = phpCAS::checkAuthentication();
// logout if desired
if (isset ( $_REQUEST ['logout'] )) {
phpCAS::logout ();
}
$serviceUrl = "https://192.168.10.144:8181/accessrights/";
?>
<html>
<head>
<title>CAS form login</title>
</head>
<body>
<?php if ($auth) {
phpCAS::serviceWeb($serviceUrl, $err_code, $accessrights);
?>
<p>Hello <strong><?php echo phpCAS::getUser(); ?></strong>! You have been authenticated with CAS. Your access rights are: <?php echo $accessrights; ?></p>
<?php } else { ?>
<h3>User login</h3>
<div>Enter your username and password here in order to log in on the website:</div>
<!-- ###LOGIN_FORM### -->
<form method="GET" action="https://192.168.10.144:8181/cas/">
<p>Username : <input type="text" name="username" /></p>
<p>Password : <input type="password" name="password" /></p>
<p>Remember me : <input type="checkbox" name="rememberMe" value="true" /></p>
<p><input type="submit" value="Login !" /></p>
<input type="hidden" name="auto" value="true" />
<input type="hidden" name="service" value="<?php echo pageURL(); ?>" />
</form>
<!-- ###LOGIN_FORM### -->
<?php } ?>
</body>
</html>
I see that checkAuthentication() fails to retrieve a Proxy Granting Ticket, but I have no clue about the reason. Any ideas? I also have a page with forceAuthentication(), and it works flawlessly.
According to your server's log, CAS is trying to callback your application via "https://xxx.xx.xx.xx/redir.php" but his encounter an SSL issue "TicketCreationException: error.authentication.credentials.bad"

ember-rails & handlebars: specified templateName does not exist for one view, but does for all others

I'm working up an ember-rails app that precompiles Handlebars assets through the rails pipeline. Everything is updated to the latest versions via bundle update.
When we load the index, the ember data is not rendered to the list, despite (app/views/gigs/index.html.erb):
<h1>Gigs</h1>
<script type="text/x-handlebars">
{{ view App.ListGigsView }}
</script>
<script type="text/javascript">
$(function() {
App.gigsController.loadAll(<%= #gigs.to_json.html_safe %>);
});
</script>
So, I checked the ListGigsView, which contains the following (app/assets/javascripts/app/views/gigs/list.js):
App.ListGigsView = Ember.View.extend({
templateName: 'app/templates/gigs/list',
gigsBinding: 'App.gigsController',
showNew: function() {
this.set('isNewVisible', true);
},
hideNew: function() {
this.set('isNewVisible', false);
},
refreshListing: function() {
App.gigsController.findAll()
}
});
Seems like the templateName is pointing fine (this is similar in, say, new.js). Nonetheless, the browser console (Google Chrome Version 25.0.1364.172) keeps returning the following:
Uncaught Error: assertion failed: You specified the templateName app/templates/gigs/list for <App.ListGigsView:ember194>, but it did not exist.
Here is the file at app/assets/javascripts/app/templates/gigs/list.handlebars:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{{#each gigs}}
{{view App.ShowGigView gigBinding="this"}}
{{/each}}
{{#if isNewVisible}}
<tr>
<td>*</td>
<td>
{{view App.NewGigView}}
</td>
</tr>
{{/if}}
</tbody>
</table>
<div class="commands">
<a href="#" {{action "showNew"}}>New Gig</a>
<a href="#" {{action "refreshListing"}}>Refresh Listing</a>
</div>
Why is the template not rendering? Running Ember.TEMPLATES in the console returns all the other view template links intact:
> Ember.TEMPLATES
=> Object {app/templates/gigs/edit: function, app/templates/gigs/event: function, app/templates/gigs/show: function, application: function}
But not the one for list. Why is that template AWOL?
For reference, I am running the following according to the browser console:
Ember.VERSION : 1.0.0-rc.1 ember.js:339
Handlebars.VERSION : 1.0.0-rc.3 ember.js:339
jQuery.VERSION : 1.9.1
-Edit: I have just discovered that including the Handlebars reference to the Event view in index.html.erb causes that template to disappear,too:
<h1>Gigs</h1>
<script type="text/x-handlebars">
{{ view App.ListGigsView }}
</script>
<script type="text/x-handlebars">
{{ view App.EventView }}
</script>
<script type="text/javascript">
$(function() {
App.gigsController.loadAll(<%= #gigs.to_json.html_safe %>);
});
</script>
Why does this happen? And how can I avoid it?
app/templates/ gets stripped from the template name by default. Try gigs/list.
For me it worked when stripping out templates, e.g. app/gigs/list.

Resources