I need to connect my front-end Javascript code to my sever-side NodeJS code. How do I do this? - client-server

We are very new to programming and have a simple question. We are developing a very simple Google search app that searches strings on Google using client-server communication. We have a simple subset of Javascript here:
var firstName = some_string
var lastName = some_string
var googleSearch = firstName + lastName;
googleSearch = JSON.stringify(googleSearch);
We need to link this code to our NodeJS code to do the actual searching.
var google = require('google');
google.resultsPerPage = 25;
var nextCounter = 0;
google(googleSearch, function(err,res) { // Note googleSearch is from
// the frontend Javascript code
// that we want to pull the data from.
if (err console.error(err)
var link = res.links[0];
console.log(link.href);
var myLink = link.href;
})
We want to take the data from the googleSearch variable from our front-end code and utilize it in our server-side code. Then we want to display the data from myLink , which is in our server-side code, back into our front-end code.

What you need to do is make an Ajax request from your front end to your server.
If you use jquery, you can do something like this
$.ajax({
url: YOUR_SERVER_URL+"/getData",
data: {
"google_search": googleSearch,
},
method: "GET",
//use data type json if your server returns json
dataType: "json",
success: function(result) {
console.log("data fetched Successfully");
//result is the data your server returned.
console.log(result);
},
error: function() {
console.log("Something went wrong, data could not be fetched");
}
});
On your server side if you are using Express with Node,
you can return JSON by doing something like this:
var app = express();
app.get('/getData', function(req, res, next) {
var google = require('google');
google.resultsPerPage = 25;
var nextCounter = 0;
//getting query data that you passed from front end
var googleSearch = req.query.google_search;
google(googleSearch, function(err, res) {
if (err console.error(err) var link = res.links[0]; console.log(link.href);
var myLink = link.href;
})
//sending json data as response
res.json(myLink);
});
If you are using localhost, then your server url will be something like "https://localhost:5000".

Related

Reading Json Form data golang

I am sending form data in JSON & serialize format to golang server using ajax. I am not able to read those data.
I am using kataras/iris golang framework.
Below is my code -
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
var Contact = {
sendMessage: function() {
return m.request({
method: "POST",
url: "/send/message",
data: JSON.stringify(jQuery('#contact-form').serializeFormJSON()),
withCredentials: true,
headers: {
'X-CSRF-Token': 'token_here'
}
})
}
}
<!-- Data looks like below, what is sent -->
"{\"first_name\":\"SDSDFSJ\",\"csrf.Token\":\"FjtWs7UFqC4mPlZU\",\"last_name\":\"KJDHKFSDJFH\",\"email\":\"DJFHKSDJFH#KJHFSF.COM\"}"
And I am trying to fetch the data from server using below code -
// Contact form
type Contact struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
}
contact := Contact{}
contact.FirstName = ctx.FormValue("first_name")
contact.LastName = ctx.FormValue("last_name")
contact.Email = ctx.FormValue("email")
ctx.Writef("%v", ctx.ReadForm(contact))
My all data is blank, How to grab the data? I am using https://github.com/kataras/iris golang framework.
One the one hand, you are sending a JSON to the server, but when fetching the parameters you are fetching them as "application/x-www-form-urlencoded", first, send the JSON parameters as JSON and not as string, remove the stringifying, i.e:
instead of:
JSON.stringify(jQuery('#contact-form').serializeFormJSON())
do:
jQuery('#contact-form').serializeFormJSON()
and in your Go file, bind it to your object:
var contact []Contact
err := ctx.ReadJSON(&contact)
good luck :)

express.cookieSession() not saving data in the cookies

I am using parse.com dynamic website to build a product website. I want to use session cookie to store some data in bowser session cookie. Here is my app.js
var express = require('express');
var parseExpressHttpsRedirect = require('parse-express-https-redirect');
var parseExpressCookieSession = require('parse-express-cookie-session');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');
app.set('view engine', 'ejs');
app.use(parseExpressHttpsRedirect());
app.use(express.bodyParser());
app.use(express.cookieParser('YOUR_SIGNING_SECRET'));
app.use(parseExpressCookieSession({
cookie : {
maxAge : 3600000
}
}));
app.use(express.cookieSession());
app.use(app.router);
I have this method in app.js which is supposed to returned items added in the cart
function getProductsInCart(req) {
var productsInCart = req.session.productsInCart;
if(!productsInCart) {
return [];
}
return productsInCart;
}
And this is the method which adds a new product in the cart
app.get('/add-cart/*', function(req, res) {
var url = req.url;
var productId = url.split('/')[2];
var productsInCart = getProductsInCart(req);
productsInCart.push(productId)
req.session.productsInCart = productsInCart;
console.log("productsInCart: " + JSON.stringify(productsInCart));
});
The problem i am facing is that getProductsInCart method always returns an empty array, which means that the session is not storing the object in the cookie. This should be simple enough and i can't understand why its not working. Any pointer would be deeply appreciated.
There were two things i was doing wrong
using req.session instead of req.cookies
using cookies as a normal java script objects.
Here is the code that worked
app.get('/add-cart/*', function(req, res) {
var url = req.url;
var productId = url.split('/')[2];
var productsInCart = getProductsInCart(req);
console.log("productsInCart: " + JSON.stringify(productsInCart));
productsInCart.push(productId);
res.cookie('productsInCart', productsInCart, {
signed: false,
expires: new Date(Date.now() + 1000000)
});
res.send(req.cookies);
});
function getProductsInCart(req) {
var productsInCart = req.cookies.productsInCart;
if(!productsInCart) {
return [];
}
return productsInCart;
}

parse.com: Cache results as a json file

For my app I have a long running task that generates stats. I would like the stats to be available to my users as a json file. Is there a way using parse to store the results of the task as a json that my users can retrieve? It would be great if there was some server side caching that I could take advantage of as well.
UPDATE
The following code takes my array of dictionaries and saves it as a file. I am now trying to store the file as part of a table called Cache. However the result is
Input: {}
Result: undefined
The code snippet looks like
var Buffer = require('buffer').Buffer;
...
var json = <array of dictionaries>;
var jsonStr = JSON.stringify(json);
var buf = new Buffer(jsonStr, 'utf8');
var json64 = buf.toString('base64');
var parseFile = new Parse.File('result', { "base64" : json64 }, 'application/json');
parseFile.save().then(function(parseFile) {
// The file has been saved to Parse.
var cache = new Cache();
attr = {};
attr['file'] = parseFile;
console.log(parseFile.url());
cache.save(attr, {
success : function(result) {
status.success("Cached");
},
error : function(result, error) {
status.error("Error: + " + error.message);
}
});
}, function(error) {
console.log(error);
status.error(error.message);
});

How to deal AJAX or XRH post request in ExpressJs, where the request use JSON from front-end to back-end?

environment:
-> Front-end: jquery that randle ajax request
-> Back-end: nodejs, expressjs (v.3.4.8).
I trying to create a simple contact form.
my front-end code:
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: { info: JSON.stringify(info) }
}).done(function(retorno){
//do something important
});
this work fine, i tested and on firebug everything from front-end is ok.
but i dont know how to deal with express that need read json from post request.
I just have it:
app.post('/contact', function(req, res){
});
The problem is in:
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
Just change the JSON ' ' to " " and works fine. I came from php and php recognize both ' ' and " " on a JSON, but nodejs just recognize strictly " ".
After some coding the result for a simple example of contact form is:
In a file common.js (front-end):
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {"nome":nome, "email":email, "assunto":assunto, "mensagem":mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: JSON.stringify(info),
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(retorno){
//do something at the end
}
In a file app.js or server.js or anything else (back-end):
var http = require("http")
, express = require('express')
, nodemailer = require('nodemailer')
, app = express();
app.use(express.json());
app.use(express.static(__dirname+'/public'));
app.post('/contact', function(req, res){
var name = req.body.nome;
var email = req.body.email;
var subject = req.body.assunto;
var message = req.body.mensagem;
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "your.user#gmail.com",
pass: "your.password"
}
});
mailOpts = {
from: name + ' <' + email + '>', //grab form data from the request body object
to: 'recipe.email#gmail.com',
subject: subject,
text: message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.send(false);
}
//Yay!! Email sent
else {
res.send(true);
}
});
});
app.listen(80, '127.0.0.2');
From this example: http://blog.ragingflame.co.za/2012/6/28/simple-form-handling-with-express-and-nodemailer

how can I get sessions to work using redis, express & socket.io?

So I am trying to get Sessions to work inside my socket.on('connection', ...)
I am trying to get this working using recent versions: Socket.io - 0.9.13, Express - 3.1.0 and latest versions of other modules.
Anyway I have tried using both modules 'connect-redis' and 'session.socket.io' and they both have similar problems.
In my code I have 2 redis stores (socketio.RedisStore and require('connect-redis')(express)), now this program all runs fine, but because express and socket.io need to share session data, I was wondering if this setup will use sessions correctly? do the session stores need to be the same object for express/socketio? A bit of a gray area to me, because the 2 RedisStore's will use the same db in the background?
I have tried using either the socket.io redisStore or the connect-redis redisStore in both places, but socket.io doesnt like the connect-redis redisStore and express doesnt like the socketio.redisStore.
If I use the connect-redis RedisStore then socket.io/lib/manager.js complains:
this.store.subscribe(...
TypeError Object # has no method 'subscribe'
If I use socketio.RedisStore then express/node_modules/connect/lib/middleware/session.js complains:
TypeError: Object # has no method 'get'
*Note I would rather get the session.socket.io plugin working, but when I do the same setup with that plugin, express (also) complains:
TypeError: Object # has no method 'get'
So is it ok that I use 2 different RedisStores for sessions, or do I need to somehow get one or the other working for both, and if so any ideas on how to fix?
My current code looks like this:
var
CONST = {
port: 80,
sessionKey: 'your secret sauce'
};
var
redis = require('redis');
var
express = require('express'),
socketio = require('socket.io'),
RedisStore = require('connect-redis')(express);
var
redisStore = new RedisStore(),
socketStore = new socketio.RedisStore();
var
app = express(),
server = require('http').createServer(app),
io = socketio.listen(server);
app.configure(function(){
app.use(express.cookieParser( CONST.sessionKey ));
app.use(express.session({ secret: CONST.sessionKey, store: redisStore }));
app.use(express.static(__dirname + '/test'));
app.get('/', function (req, res) {res.sendfile(__dirname + '/test/' + 'index.htm');});
});
io.configure(function(){
io.set('log level', 1);
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
io.set('store', socketStore);
});
io.sockets.on('connection', function(socket){
socket.emit('message', 'Test 1 from server')
});
server.listen( CONST.port );
console.log('running...');
inside the io.configure, you have to link the socket with the http session.
Here's a piece of code that extracts the cookie (This is using socket.io with xhr-polling, I don't know if this would work for websocket, although I suspect it would work).
var cookie = require('cookie');
var connect = require('connect');
var sessionStore = new RedisStore({
client: redis // the redis client
});
socketio.set('authorization', function(data, cb) {
if (data.headers.cookie) {
var sessionCookie = cookie.parse(data.headers.cookie);
var sessionID = connect.utils.parseSignedCookie(sessionCookie['connect.sid'], secret);
sessionStore.get(sessionID, function(err, session) {
if (err || !session) {
cb('Error', false);
} else {
data.session = session;
data.sessionID = sessionID;
cb(null, true);
}
});
} else {
cb('No cookie', false);
}
});
Then you can access the session using:
socket.on("selector", function(data, reply) {
var session = this.handshake.session;
...
}
This also has the added benefit that it checks there is a valid session, so only your logged in users can use sockets. You can use a different logic, though.
Looking at your last note (won't be able to share its state over multiple processes using redis) I had the same problem and found a solution:
var express = require("express.io");
var swig = require('swig');
var redis = require('redis');
var RedisStore = require('connect-redis')(express);
workers = function() {
var app = express().http().io();
app.use(express.cookieParser());
app.use(express.session({
secret: 'very cool secretcode',
store: new RedisStore({ client: redis.createClient() })
}));
app.io.set('store', new express.io.RedisStore({
redisPub: redis.createClient(),
redisSub: redis.createClient(),
redisClient: redis.createClient()
}));
app.get('/', function(req, res) {
res.render('index');
});
app.listen(3000);
app.io.route('ready', function(req){
//setup session stuff, use session stuff, etc. Or make new routes
});
};
cluster = require('cluster');
numCPUs = require('os').cpus().length;
if (cluster.isMaster)
{
for (var i = 0; i < numCPUs; i++)
{
cluster.fork();
}
}
else
{
workers();
}

Resources