I've wrote this service using node, it works but i don't know how to call it from an angularjs controller, i nedd to call the post method
this is the service:
var app = require('express')();
var http = require('http').Server(app);
var mysql = require('mysql');
var bodyParser = require("body-parser");
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'repositorio',
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',function(req,res){
var data = {
"error":1,
"Usuarios":""
};
connection.query("SELECT * from usuario",function(err, rows, fields){
if(rows.length != 0){
data["error"] = 0;
data["Usuarios"] = rows;
res.json(data);
}else{
data["Usuarios"] = 'Usuarios no encontrados..';
res.json(data);
}
});
/*var data = {
"Data":""
};
data["Data"] = "Welcome to Book Store DEMO...";
res.json(data);*/
});
app.post('/usuario',function(req,res){
var Email = req.query.correo;
var Password = req.query.contrasena;
var Nombres = req.query.nombres;
var Apellidos = req.query.apellidos;
var Usuario = req.query.usuario;
var data = {
"error":1,
"Usuario":""
};
console.log("Email: "+Email+" Password "+Password+" Nombres "+Nombres+" Apellidos "+Apellidos+" Usuario"+Usuario);
if(!!Email && !!Password && !!Nombres && !!Apellidos && !!Usuario){
var user ={usu_correo: Email,usu_contrasena: Password,usu_nombres:Nombres,usu_apellidos: Apellidos,usu_usuario:Usuario}
connection.query('INSERT INTO usuario SET ?',user,function(err, rows, fields){
if(!!err){
data["Usuario"] = "Error Adding data";
}else{
data["error"] = 0;
data["Usuario"] = "Usuario adicionado con éxito";
}
res.json(data);
});
}else{
data["Usuario"] = "Please provide all required data";
res.json(data);
}
});
http.listen(8080,function(){
console.log("Connected & Listen to port 8080");
});
and this is me trying to connect it with angular, i need help please
var app = angular.module('el_acorde_web', []);
app.controller('usuarioscontroller', function($scope, $http)
{
$scope.usuario = {};
$scope.usuario.correo = "davidstl5#gmail.com";
$scope.usuario.nombres = "David Fernano";
$scope.usuario.apellidos = "Sotelo";
$scope.usuario.contrasena = "lakjsdlfkja";
$scope.usuario.usuario = "davidstl5";
$scope.registrar = function(){
$http.post('http://localhost:8080/usuario', $scope.usuario)
.success(function(data)
{
alert(data);
})
.error(function(data)
{
alert('Error:' + data);
});
}
});
Your code looks fine, can I see the HTML code where you are calling the registrar function? Looks like you only have to add the ng-click directive if everything else is working, and for a best practice I would create a factory or a service and call a function there that interacts with the Node app.
I found the solution!
Chrome is the problem we install https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
and then use:
$scope.registrar = function(){
alert("Entre");
/*$http.post('http://localhost:8080/usuario', $scope.usuario)
.success(function(data)
{
alert(data);
})
.error(function(data)
{
alert('Error:' + data);
});*/
var datos = {correo: $scope.usuario.correo, contrasena: $scope.usuario.contrasena,
nombres:$scope.usuario.nombres, apellidos: $scope.usuario.apellidos,
usuario: $scope.usuario.usuario};
var request = $http({
method: "POST",
url: "http://localhost:8080/usuario",
data: datos,
headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(datos),
'Access-Control-Allow-Origin': "*"}
});
request.success(
function( data ) {
alert(data);
}
);
request.error(
function( data ) {
alert(data);
}
);
}
and everything works!
Related
Good Morning Everyone,
I have made a web app using node.js and express. I got Nodemailer to send an email and my AJAX is sending the parsed JSON data to express, but I am having trouble getting that from data into nodemailer. My Ajax is sending the JSON to express I have confirmed that with DEV Tools, but I'm at a loss on how to put the JSON into nodemailer. Any help would be much appreciated.
/* contact Route: contact.js */
var express = require('express');
const contact = express.Router();
var path = require('path');
const bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
contact.use(bodyParser.json() );
contact.use(express.static(__dirname + 'portfolio'));
contact.get('/contact', (req,res,next) => {
res.sendFile(path.join(__dirname, '../html-files', 'contact.html'));
console.log('this works');
});
contact.post('/contact', (req,res) => {
/*const data = req.body.data;
const from = data.email;
const text = data.message;*/
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'augustshah#02pilot.com',
pass: 'hgahalzecelxdxis'
}
});
var mailOptions = {
from: this.email,
to: 'augustshah#02pilot.com',
subject: 'Quote',
text: this.message
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
})
module.exports = contact;
/* Jquery: script.js*/
//const { json } = require("body-parser");
//var requirejs = require('requirejs');
//const { json } = require("body-parser");
$('#submit').on('click', function(e) {
e.preventDefault();
const name = $("#name").val();
const email = $("#email").val();
const message = $("#message").val();
var $form = $( this ),
url = $form.attr( "action", "/contact");
const data = {
name: name,
email: email,
message: message
};
$.ajax({
type: "POST", // HTTP method POST or GET
url: "/contact", //Where to make Ajax calls
dataType: "json", // Data type, HTML, json etc.
data: JSON.stringify(data), //Form variables
success: function() {
alert("Your Email has been sent");
},
error: function() {
alert("Your Email has not sent. Try Again. ");
}
})
});
FIXED: It was simple. in my script.js, I didn't have my contentType set. I set it to 'application/json' and that fixed my issue.
I have recently started using Node.js and jQuery and I can't figure out what's wrong in my project.
I have a client application that sends a post request to a node js server; this server gets the datas from the post and performs a query; finally it should send back to the client a json containing the informations retrieved from the previous query. The problem is that the response sent by node js is an empty object( {} ) and I don't know why.
Here my source code:
Node JS:
var http = require("http");
var url = require('url');
var querystring = require('querystring');
var express = require('express');
var cookieParser = require('cookie-parser');
var mysql = require('mysql');
var con = mysql.createConnection({
host: "",
user: "",
password: "",
database : ''
});
var app = express();
app.use(express.static(__dirname + '/public'))
.use(cookieParser());
app.post('/search',function(req, res) {
if (req.method == 'POST') { //PUT Only
var body = '';
req.on('data', function (data){body += data;});
req.on('end', function () {
var post = querystring.parse(body);
console.log("Dati in ingresso > " + JSON.stringify(post));
//res.writeHead(200, {'Content-Type': 'text/plain'})
query("SELECT Nome FROM Mood WHERE Nome LIKE \'" + post.data + "%\'",res);
});
}else{
console.log("Not POST request")
res.end();
}
});
var query = function(q,res) {
var results = {};
con.query(q, function (err, result, fields) {
if (err) throw err;
results = JSON.stringify(JSON.parse(JSON.stringify(result))[0].Nome);
console.log("Risultati query: ");
console.log(results);
});
res.json(results);
res.end();
}
app.listen(8888);
Client:
$("document").ready(function () {
$('#search-box').on('input propertychange', function(e){
var input = $(this).val();
var array = ['prova1','prova2','prova3'];
var ul = $('#results-options ul');
$.ajax({
type: "POST",
url: "/search",
data: {data : input},
contentType: "application/json",
success: function(d) {
console.log(d);
console.log(JSON.stringify(d));
console.log(JSON.parse(d));
},
error: function(d) {
console.log("Error");
}
});
$('#results-options').show();
});
$("#results-options").on('click',function (e) {
$('this').show();
e.stopPropagation();
})
$(document).on('click', function(){
$('#results-options').hide();
})
});
As I stated above, your query function is sending back a response before the query to the database has finished. That's why it is coming back empty. I moved the res.json(results); res.end(); code inside the callback of the DB query.
var query = function(q,res) {
var results = {};
con.query(q, function (err, result, fields) {
if (err) throw err;
results = JSON.stringify(JSON.parse(JSON.stringify(result))[0].Nome);
console.log("Risultati query: ");
console.log(results);
// I moved the code here
res.json(results);
res.end();
});
// Your old code
// res.json(results);
// res.end();
};
I have the following code:
serverside.js:
var express = require('express');
var app = express();
app.post('/LEDon', function(req, res) {
var obj = res;
console.log('LEDon button pressed!');
// Run your LED toggling code here
});
app.listen(1337);
clientside.js:
$('#ledon-button').click(function() {
var test = "123";
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
data: JSON.stringify(test),
contentType: 'application/json'
});
});
view.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='ledon-button'>LED on</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src='clientside.js'>
</script>
</body>
</html>
Nothing happens when I click the button. But if I remove some lines from clientside.js it works:
$('#ledon-button').click(function() {
var test = "123";
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
});
});
But this way no JSON-file is being sent. I tried looking at tutorials but found nothing. What am I missing?
So this is how I solved it:
clientside:
function getData(number) {
var teamId = number; // in data!!
$.ajax({
type: "POST",
url: "http://localhost:80/getdata",
crossDomain:true,
dataType: "json",
data:JSON.stringify(teamId)
}).done(function ( data ) {
var myJSON = JSON.stringify(data);
}
server side:
var express = require('express');
var app = express();
// Load the http module to create an http server.
var http = require('http');
const mysql = require('mysql');
app.post('/getdata', function(request, response) {
var store = '';
var query;
var query2;
// First you need to create a connection to the db
const con = mysql.createConnection({
host: 'db.host.net',
user: 'dbuser',
password: 'mypw',
database: 'dbname',
});
request.on('data', function(data) {
store += data;
query = "regular db query";
con.connect((err) => {
if (err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection was established');
});
con.query(query, (err, rows) => {
if (err) throw err;
// handling query stuff
query2 = "regular db query";
// getting db query
con.query(query2, (err, rows2) => {
// handling query stuff
if (err) throw err;
myJSON = {
"var1": "data1",
"va2": "data2"
}
console.log("\nThe JSON resultset: " + JSON.stringify(myJSON));
response.end(JSON.stringify(myJSON));
con.end();
});
});
console.log("DB connection ended");
});
request.on('end', function() {
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
});
}); app.listen(80);
Let me know if something is unclear or can be done better.
I have a file, controller.js in trying to import functionality into app.js.
I keep getting syntax errors:
, expected
statement expected
Simple to fix I though however when I fix one 10 more pop up, So can some one look at my code and see what doing wrong ?
app.js
Promise.all([controller.firstFunction(), controller.secondFunction()]) .then(controller.thirdFunction);
controller.js
module.exports = {
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // Start the server
// app.listen(port);
// app.use(bodyParser.json()); // support json encoded bodies
// app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
// console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// app.use('/', router);
var firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
var secondFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
};
function thirdFunction(result) {
return new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.error(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
};
This is because you wrapped your code inside an object, {} tags.
You have a couple of options, my suggestion is to use Prototypes like so
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // Start the server
// app.listen(port);
// app.use(bodyParser.json()); // support json encoded bodies
// app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
// console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// app.use('/', router);
function Functions(){};
Functions.prototype.firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
Functions.prototype.secondFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
};
Functions.prototype.thirdFunction(result) {
return new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.error(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
module.exports = Functions;
Then you would create a instance of the class within the file you require it (in this case app.js)
var myFunctions = new Functions();
From there you can access your methods using:
myFunctions.firstFunction();
If you however wanted to go on about the way you have done so already, you should use object structure like so
module.exports = {
firstFunction : function()
{
//Function Body
},
secondFunction : function()
{
//Function Body
}
}
Issue with you code is :
you were using var inside module.export and that means you are declaring var inside export that is not valid,
module.export should be in json format.
Try this code :
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // Start the server
// app.listen(port);
// app.use(bodyParser.json()); // support json encoded bodies
// app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
// console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// app.use('/', router);
module.exports = {
firstFunction : function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
},
secondFunction : function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
},
thirdFunction : function(result) {
return new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.error(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
};
You need to use object notation inside of an object ( module.exports):
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
module.exports = {
firstFunction() {
return new Promise(function(){
...
});
},
secondFunction(){},
thirdFunction(){}
};
and exporting dependencies and passwords is not really useful...
I want to send form data to node.js server using Ajax and I am fallowing the below approach to send data.
I am not getting how receive it in node.js server program I am not using express framework for node.js
client.HTML
<script>
function myFunction() {
var region = document.getElementById("region").value;
var os = document.getElementById("os").value;
var data = {};
data.region = region;
data.os = os;
$.ajax({
type: 'post',
datatype: 'jsonp',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://127.0.0.1:8083/', //node.js server is running
success: function(data) {
alert("success");
}
});
</script>
<form>
<select id="region" name="region" class="region"></select>
<select id="os" name="os" class="os"></select>
<input type="button" value="search" class="fil_search" onclick="myFunction()"/>
</form>
server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var result1=[];
var result2=[];
var result3=[];
var result4=[];
var result5=[];
var result6=[];
var result7=[];
var i=0;
var region;
var os;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect("mongodb://192.168.1.22:27017/test", function(err, db) {
if(err) { return console.dir(err); }
else {
app.get('/',function(req, res) {
var url_parts = url.parse(req.url, true);
var url_parsed = url.parse(req.url, true);
"i want data here from ajax to perform"
console.log("connected");
var instance = db.collection('instance');
var region = db.collection('region');
region.findOne(({$and: [{"region_name": region_name},{"os_type": os}]}), function(err, result){
if(err){
throw(err);
}
else{
console.log(region);
var newr = result.inst_name;
instance.find({ "inst_id": { "$in": newr } }).toArray(function(err, resultn){
if(err){
throw(err);
}
else{
var len=resultn.length;
console.log(resultn);
console.log(len);
for(var i=0;i<len;i++)
{
result1[i]=resultn[i].inst_type;
result2[i]=resultn[i].vcpu;
result3[i]=resultn[i].memory_gib;
result4[i]=resultn[i].storage;
result5[i]=resultn[i].phy_processor;
result6[i]=resultn[i].clock_spd;
result7[i]=resultn[i].netwk_pef;
}
var wstream = fs.createWriteStream('myOutput.txt');
wstream.write(result1.toString()+"~"+result2.toString());
//var str = "Hi man"
res.writeHead(200, {'Content-Type':'text/html'});
//res.end(url_parsed.query.callback+'("'+resultn.toString()+'")');
res.end(url_parsed.query.callback+'("'+result1.toString()+"~"+result2.toString()+"~"
+result3.toString()+"~"+result4.toString()+"~"+result5.toString()+"~"+result6.toString()
+"~"+result7.toString()+'")');
}
});
}
});
}).listen(process.env.PORT || 8083);
}
});
I am not getting how to receive data in node.js server program and after receiving data I want process on that data and send back processed data to same HTML page.
If you have app.use(bodyParser.urlencoded({ extended: true })); in your server.js file then using bodyParser you can retrieve data from ajax as given below:
app.post('/', function(req, res) { //your ajax should also post to url: '/'
var region = req.body.region,
os = req.body.os;
// ...
});