Login form, Angular 5 and nodeJS - node.js

I'm trying to implement a form using Angular5 and NodeJS
The original form, I was given, is set up as:
<form action="https://www.myUrl.co.uk/signin" method="post">
<table border="0">
<tbody>
<tr>
<td>Username:</td>
<td><input id="Username" name="email" type="text" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input id="Password" name="password" type="password" /></td>
</tr>
<tr>
<td></td>
<td><input name="submit" type="submit" value="Login" /></td>
</tr>
</tbody>
</table>
</form>
I've noticed that in the headers the form Data sends:
email=some#email.co.uk&password=omsmmsms&submit=Login
In order to use it within Angular I've set app as follows
template form:
<form name="clientForm" id="clientForm" novalidate [formGroup]='clientForm' (ngSubmit)="submitForm()">
<div class="row control-group">
<label for="userName">UserName</label>
<input formControlName="userName" type="text" class="form-control" placeholder="UserName" id="userName">
<label for="password">Password</label>
<input formControlName="password" type="password" class="form-control" placeholder="password" id="password">
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-lg" >Send</button>
</div>
</div>
</div>
</form>
The component file:
submitForm() {
const userName = this.clientForm.get('userName').value;
const password = this.clientForm.get('password').value;
this.contactService.client(userName, password)
.subscribe((response) => {
if (response.msg === 'sent') {
this.success = response.sucess;
this.clientForm.reset();
}
});
}
This subscribes to a observable function in a service:
public client(userName, password): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/X-www-form-urlencoded',
})
};
let body = "Username="+userName+"&password="+password;
return this.http.post(this.url+'contact/client', body, httpOptions)
.map((response) => {
//window.open('https://www.accountancymanager.co.uk/myinfo', '_blank');
return response;
})
.catch((error: Response) => Observable.throw(error.json()) )
}
The service connect to a NodeJS route below:
router.post('/client', function (req, res) {
var options = {
url: 'https://www.accountancymanager.co.uk/signin',
method: 'POST', // Don't forget this line
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-MicrosoftAjax': 'Delta=true',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
},
form: {
'Username' :req.body.Username,
'Password' :req.body.password
}
};
request(options, (err, response, body) => {
if (err) {
console.log(err);
} else {
res.json('something')
console.log(options.form);
}
});
});
I get no errors from the above, but how do I send the user in the Angular app to the login page after success?
Simply redirecting doesn't work.
Or is there another way?
Maybe sending all data from the service, no NodeJS?
Let me know if unclear

put this in your code:
import {Router} from '#angular/router';
constructor(private router: Router) {
}
submitForm() {
const userName = this.clientForm.get('userName').value;
const password = this.clientForm.get('password').value;
this.contactService.client(userName, password)
.subscribe((response) => {
if (response.msg === 'sent') {
this.success = response.sucess;
// this.clientForm.reset();
this.router.navigate(['your route']);
}
});
}

Related

error Sorry, you are not allowed to post with this username

I used the following code to upload the file from node js to Wordpress;
app.js codes:
axios = require('axios');
FormData = require('form-data');
socket.on('uploadFile', function (data) {
var formData = new FormData();
formData.append("image", data);
axios.post('https://fxalion.com/wp-json/wp/v2/media', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
});
my custom js codes:
$('.uploadFile').on('submit',function (e){
e.preventDefault();
var imagefile = document.querySelector('#file');
socket.emit('uploadFile', imagefile.files[0]);
});
my html codes:
<form class="uploadFile h-100 d-flex align-items-center justify-content-center flex-column">
<div class="mb-3">
<input type="file" id="file" class="form-control" aria-label="file example" required>
</div>
<div class="mb-3">
<button class="btn btn-primary" type="submit">آپلود</button>
</div>
</form>
But I get this error:
data: {
code: 'rest_cannot_create',
message: 'Sorry, you are not allowed to post with this username.',
data: { status: 401 }
}
please help me...

error TypeError: Failed to fetch - express js

I have tested the api is working fine in postman but when i try to run on localhost it shows this error: TypeError: Failed to fetch .
I have tried using corsOptions and Access-Control-Allow-Origin but both didn't solved my error.
When I try to run on localhost, it shows output in terminal:
result= { NAME: 'myname',
EMAIL: 'anymail#gmail.com',
IS_VERIFIED: 1,
PSWD: 'password' }
true
true
success
Please help me out, I have spent more than 50hrs but didn't found any solution.Thanks
Server-side code(node):
app.post('/checkLogin', cors(corsOptions), function (req, res) {
var result = {};
let Inputdata = { email: req.body.email, pass: req.body.password };
console.log("Input data=", Inputdata);
let selectQuery = `SELECT * FROM "schema"."tablename" WHERE "EMAIL"='${Inputdata.email}';`
ibmdb.open(connStr, function (err, conn) {
//blocks until the query is completed and all data has been acquired
if (err)
{
console.log("error in db connection:",err);
}
var rows = conn.querySync(selectQuery);
result = rows[0];
console.log("result=", result);
if (result != undefined)
{
console.log(result.PSWD === Inputdata.pass)
console.log(result.IS_VERIFIED == 1)
if (result.PSWD == Inputdata.pass && result.IS_VERIFIED == 1) {
console.log("success")
res.status(200).send({ data: { token: 'this is a pretend token' } });
}
else {
console.log("Failed")
res.status(401).send({
error: { code: 401, message: 'invalid username or password.' },
});
}
}
else
{
res.status(401).send({
error: { code: 401, message: 'invalid username or password.' },
});
}
});
});
client-side code(js):
function doLogin() {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"email":document.getElementById('inputEmail').value,"password":document.getElementById('inputPassword').value});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://localhost:50000/checkLogin", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
my html form:
<form class="form-signin">
<!-- Input email address-->
<div class="form-label-group">
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputEmail">Email address</label>
</div>
<!-- Input password-->
<div class="form-label-group">
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<label for="inputPassword">Password</label>
</div>
<!-- Input check box to remember password-->
<div class="custom-control custom-checkbox mb-3">
<input type="checkbox" class="custom-control-input" id="customCheck1">
<label class="custom-control-label" for="customCheck1">Remember password</label>
</div>
<!-- Login button-->
<button class="btn btn-lg btn-primary btn-block text-uppercase" onclick="doLogin()">Sign in</button>
<hr class="my-4">
<!--signup libk -->
<div class="text-center">
<label >Not a member ?
Sign up Now
</label>
</div>
</form>

React, Node: Variable shows undefined on app.post()

Not sure if I've done it correctly on the server or client side, but in the client side when I console.log(values) they appear, but in server, I get undefined. But when i do enter the right credentials for a user in the database i get status:ok, so something is found. And also a extra bug is i cannot to the post request twice, then i get the error: Error: Cannot enqueue Handshake after invoking quit.
Client Code:
class Login extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
const email = data.get('email');
const password = data.get('password');
fetch('/authentication', {
method: 'POST',
body: JSON.stringify({
"email": email,
"password": password
}),
}).then(function (response) {
if (response.ok) {
alert("Login Successful!");
} else {
console.log("Failed");
}
});
console.log("Email: " + email);
console.log("pwd: " + password);
}
render() {
return (
<form className="col s12 m12 l12" onSubmit={this.handleSubmit}>
<div className="row">
<div className="col s12 center-align">
<img className="logo" src="images/bibdata-center.png" alt="BibData Logo"/>
</div>
<div className="input-field col s12">
<i className="material-icons prefix">email</i>
<input id="email" name="email" type="email" className="validate" onChange={this.handleEmailChange}/>
<label htmlFor="email">Email</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<i className="material-icons prefix">lock</i>
<input id="password" name="password" type="password" className="validate" onChange={this.handlePasswordChange}/>
<label htmlFor="password">Password</label>
</div>
</div>
<div className="row">
<div className="col s12 m6 l6 center-align">
<button className="btn waves-effect btn-large waves-light" type="submit" value="Submit" name="action">Sign in
<i className="material-icons right">send</i>
</button>
</div>
<div className="col s12 m6 l6 center-align">
<button className="btn waves-effect btn-large waves-light blue" type="submit" name="action"
onClick={() => renderReactComponent(newUser, 'root')}>
Register
</button>
</div>
</div>
<div className="row">
<div className="col s12 center-align">
<a href="#" onClick={() => renderReactComponent(forgotPassword, 'root')}>
<span className="helper-text grey-text text-darken-1"
data-error="wrong" data-success="right">
Forgot password?
</span>
</a>
</div>
</div>
</form>
);
}
}
And Server Code:
app.post('/authentication', function (req, res) {
connection.connect();
let email = req.body.email;
let password = req.body.password;
console.log(email);
console.log(password);
connection.query('SELECT * FROM user WHERE email = ? AND password = ?',
[email, password], function (error, results, fields) {
if (error) {
return res.status(500).send(error);
}
return res.send({ error: false, data: results, message: 'ok'})
});
connection.end();
});
All help will be appreciated!
When you make your fetch call to /authentication endpoint, you are sending serialized JSON data in your request body. The server however has no means of knowing that you have actually sent an JSON. When posting JSON, you must indicate that by providing appropriate content-type header.
In this case your fetch options (2nd param) should have one more property like this:
...
headers: {
"Content-Type": "application/json",
},
...
This is assuming, you have already setup body-parser or another similar module on your server side code which can parse JSON request body.

How to initiate nodejs file that contains oauth2 procedure and api calls by clicking a button in angular 2 template

I'm very new to angular2/nodejs and am trying to take form data and push it to hubspot. I really need some help on this one and feel like i've tried everything. My code is below:
form.component.html
<div xmlns="">
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<div class="row">
<div class="col-lg-12 form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
class="form-control"
name="email"
ngModel
required
[pattern]="'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$'"
>
</div>
<div class="row moveRight">
<div class="col-lg-12 form-group">
<label for="firstname">First Name</label>
<input
type="text"
id="firstname"
class="form-control"
name="firstname"
ngModel
required
>
</div>
</div>
<div class="row moveRight">
<div class="col-lg-12 form-group">
<label for="lastname">Last Name</label>
<input
type="text"
id="lastname"
class="form-control"
name="lastname"
ngModel
required
>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<button class="btn btn-success" id="startnode" type="submit" [disabled]="!f.valid" (click)="form.js">Submit</button>
</div>
</div>
</div>
form.js
var request = require('request');
request({
url: 'https://app.hubspot.com/oauth/authorize?client_id=CLIENT-ID&scope=forms%20automation&redirect_uri=https://www.example.com/',
method: 'POST',
auth: {
user: 'username',
pass: 'Password'
},
form: {
'grant_type': 'client_credentials'
}
}, function(err, res) {
var json = JSON.parse(res.body);
console.log ("Access Token:", json.access_token);
});
var request = require('request');
var accessToken = "ACCESS TOKEN";
request({
url: 'https://api.someapi.com/blah/something',
auth: {
'bearer': accessToken
}
}, function(err, res) {
console.log(res.body);
});
//require Node modules
var https = require('https');
var querystring = require('querystring');
// build the data object
var postData = querystring.stringify({
'email': req.body.email,
'firstname': req.body.firstname,
'lastname': req.body.lastname,
'hs_context': JSON.stringify({
"hutk": req.cookies.hubspotutk,
"ipAddress": req.headers['x-forwarded-for'] || req.connection.remoteAddress,
"pageUrl": "https://localhost:4200 ",
"pageName": "Example Title"
})
});
// set the post options, changing out the HUB ID and FORM GUID variables.
var options = {
hostname: 'forms.hubspot.com',
path: '/uploads/form/v2/GUID/CLIENT-ID',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
}
// set up the request
var request = https.request(options, function(response){
console.log("Status: " + response.statusCode);
console.log("Headers: " + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function(chunk){
console.log('Body: ' + chunk)
});
});
request.on('error', function(e){
console.log("Problem with request " + e.message)
});
// post the data
request.write(postData);
request.end();
So 4 things I need help with
1) Ensure I am connecting my form fields to the nodejs fields correctly
2) initialize all the nodejs code after clicking the submit button
3) validate the access_token that I return, I can use to complete the authorization process to continue to the API post call.
4) is my api post request correct.
Thank you in advance

how to display data after form submit using expressjs

**app.js** Code
app.get('/', function (req, res) {
res.render('index', {
data: docsData,
title: "EJS example",
header: "Some users"
});
});
app.post('/', function (req, res) {
var jname= req.body.firstname;
var lname= req.body.lastname;
var jemail= req.body.email;
var collection = dbConnect.collection('users');
var document={name:jname, lastname:lname, email:jemail};
collection.insert(document, {w: 1}, function(err, records){
console.log("Record added as "+records[0]._id);
});
dbConnect.collection("users").find({"name":jname}).toArray(function(err, docsData) {
console.log('checking error',err, docsData);
res.render('index', {
data: docsData,
title: "AJT Family",
header: "Some users"
});
});
});
**html code**
<div align="center" ng-controller="FormCtrl">
<form name="form" ng-submit="submitForm()" novalidate>
<table>
<tr><td>Name:</td>
<td>
<input id="firstname" type="text" ng-model="regform.firstname" name="firstname" required="" />
</td>
<td>
<div ng-show="form.$submitted || form.firstname.$touched">
<div ng-show="form.firstname.$error.required">Enter your name.</div>
</div>
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
<input id="lastname" name="lastname" type="text" ng-model="regform.lastname" required>
</td>
<td>
<div ng-show="form.$submitted || form.lastname.$touched">
<div ng-show="form.lastname.$error.required">Enter your Last name.</div>
</div>
</td>
</tr>
<tr>
<td>E-mail:</td>
<td><input id="email" type="email" ng-model="regform.email" name="uEmail" required="" /></td>
<td>
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required">Enter your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
</td>
</tr>
</table>
<input type="button" ng-click="reset(form)" value="Reset" />
<input type="submit" ng-disabled="!form.$valid" value="Save" />
<p id="hu"></p>
</form>
</div>
<%if(data) {%>
<h1>Users</h1>
<% data.forEach(function(user){ %>
<br>
<table>
<tr><td>Name: </td><td><%= user.name %> <%= user.lastname %></td></tr>
<tr><td>Email: </td><td><%= user.email %></td></tr>
</table>
<% }) %>
<% } %>
</body>
</html>
**javascript**
var result;
var app = angular.module('formExample', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.data = {};
$scope.submitForm = function() {
formData = $scope.regform;
console.log("posting data....");
var request = $http({ url: '/',data: $scope.regform, method: 'post' });
console.log(formData);
};
});
here I can save data on mongodb using expressjs. I need to display data after form submission. Here nothing is displaying after form submission. How to display that saved content in html using embedded Javascript.
What you'll want to do is change your res.render() call to do something like this:
res.render('index', {
data: docsData,
title: 'AJT Family',
header: 'Some Users',
body: req.body, // This is your form data as a JSON object.
});
Then, in your index template, you'll have access to your form data to display however you want, if you're using Jade, for instance, you might want to say like:
h1 Data!
p #{body}

Resources