Passing a sql table created with alasql from Server (node.js) to Client (ejs) - node.js

I would be very glad to get some help on the following topic, given I didn't manage to get through it.
My objective is to gather some data on the server side (so far I'm using alasql to transform my CSV fil into a sql table), and then pass it as a parameter to the client side, to perform other sql operations on Client side (again with alasql).
So far, I suceeded in
Transforming the CSV file into a sql table thanks to alasql
Passing a parameter from the Server side to the Client Side
But I did not manage to
Pass the sql table itself from the Server side to the Client side as a parameter
My best result in trying to do so is
`input=[object Object],[object Object],...`
instead of the sql table I would expect,which gives an error
My code on the Server side is the following:
var express = require('express');
var session = require('cookie-session'); // Charge le middleware de sessions
var bodyParser = require('body-parser'); // Charge le middleware de gestion des paramètres
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var alasql=require('alasql');
var app = express();
var input=0;
alasql('SELECT * FROM CSV("public/data/output.csv",{separator:";"})',[],function(data){
input=data;
console.log(1)
});
/* On utilise les sessions */
app.use(session({secret: 'TBC'}))
/* S'il n'y a pas de todolist dans la session, on en crée une vide sous forme d'array avant la suite */
.use(function(req, res, next){
next();
})
.use(express.static(__dirname + '/public'))
/* On affiche la todolist et le formulaire */
.get('/segmentation_clients', function(req, res) {
console.log(input);
var Commercial='U.Morel';
res.render('segmentation_clients.ejs', {Commercial:'U. Morel',input:input});
})
.listen(8080);
The beginning of the JS code on the Client side (segmentation_clients.ejs):
var Commercial="<%=Commercial%>";
var input= <%=input%>;
console.log(input);
The output of the code (ok for the #Commercial parameter but not ok for the #input SQL table):
enter image description here
I would greatly appreciate your help on this topic
Thanks a lot
Stéphane

I finally got the solution:
On Server side, I replacedinput:input
with
input:JSON.stringify(input)
On Client side, I replaced var input= <%=input%>;
with
var input= <%-input%>;
The first problem was a problem of format (solved by transforming the input in a JSON format), and the second problem was about evaluating the data inside the arry with "-" instead of only reading it "=", as far as I understood
Best
Stéphane

Related

JSONSerialization makes incorrect JSON object. Swift

I'm creating an iOS app that connects to a NodeJS server. The get method works fine but the POST method has problems.
var urlRequest = URLRequest(url: "http://localhost:3000/register")
urlRequest.httpMethod = "POST"
let info: [String:Any] = ["username": "username", "password":"username", "email":"username#username.com"]
do {
let jsonInfo = try
JSONSerialization.data(withJSONObject: info, options[])
urlRequest.httpBody = jsonInfo
} catch {
print("ERROR")
return
}
The request gets sent but something goes wrong with JSONSerialization because this is the JSON data that the server gets:
{'{"email":"username#username.com","username":"username","password":"username"}': '' }
This is what I'm going for:
{"email":"username#username.com","username":"username","password":"username"}
This is part of the server code:
const express = require('express');
const bodyParser = require('body-parser');
var app = express();
var allowMethods = function(req, res, next) {
res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE');
next();
}
http.createServer(app).listen(3001);
console.log("Server started");
app.use(bodyParser.urlencoded({extended: true}));
app.use(allowMethods);
const _ = require('lodash');
let b = _.pick(req.body, ['username', 'password', 'email']);
Any ideas on what I'm doing wrong? I'd like to avoid using alamofire if possible. I've tried changing the format of the dictionary but always turns out as:
{ 'the whole dictionary is the key': ''}
I've also tried using pretty print and this was the result:
{ '{\n "email" : "username#username.com",\n "username" : "username",\n "password" : "username"\n}': '' }
Any help is appreciated. Thank you!
EDIT:
I tried Mike Taverne's suggestions.
I changed the server code to use this instead:
app.use(bodyParser.json());
But I receive an empty body from the simulator.
I also added these to the swift code:
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
But the server also receives an empty body and by empty body I mean the data I'm trying to send is received as empty by the server. When I check the httpBody the data is there but for some reason the server doesn't receive it.
I believe your Swift code is fine. When I did this in a playground:
print(String(data: urlRequest.httpBody!, encoding: String.Encoding.utf8)!)
It printed:
{"username":"username","password":"username","email":"username#username.com"}
I'm not an expert on body-parser, but I think that instead of this:
bodyParser.urlencoded({extended: true})
You should be using this:
bodyParser.json([options]) //not sure which options exactly you need
You may need to set Content-Type: application/json header as well. Refer to the body-parser documentation for more info.
I solved it by changing the data itself. Instead of forcing it to pass JSON I passed it as a string encoded using UTF8
let dataString = "username=username&password=username&email=username#username.com"
urlRequest.httpBody = dataString.data(using: .utf8)
I got the answer by using the method in this post:
HTTP Request in Swift with POST method

How can i have access to my node js application everywhere?

I need some explanation. My node JS application is only accessible for me (the network). How can i have make my node js application online ? Do i necessary need to redirect the application via the port 80 ? I need to have access to my application everywhere via the port 8124. http://example.com:8124.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var i;
/**
* Gestion des requêtes HTTP des utilisateurs en leur renvoyant les fichiers du dossier 'public'
*/
app.use('/', express.static(__dirname + '/public'));
/**
* Lancement du serveur en écoutant les connexions arrivant sur le port 8124
*/
http.listen(8124, function () {
console.log('Server is listening on *:8124');
});
In the function listem, do i have to specify something specific as second parameter ? Also is it safe to let access to people with that type of url ?
I'd suggest you look into developing on Cloud9. There are no firewall issues to worry about and you can work on your project anywhere and behind any firewall.
If you insist on developing on your own network, then you may want to look into changing your hostname file. You can map example.com to map to localhost very simply.

nodejs express 3 framework session destroying issue

I'm using nodejs with Express 3 framework and I have an issue with deleting one specific session, here is the code I'm using :
app.js
var express = require('express');
................
................
app.use(express.cookieParser());
app.use(express.session({secret : 'asxcfrgth'}));
app.use(app.router);
app.get('/User', function(req, res){
req.session.login = "Invalid username";
req.session.password= "Invalid password";
console.log(req.session.login);
console.log(req.session.password);
req.session.destroy();
});
req.session.destroy will delete all my sessions so is there a way to only destroy the first session and leave the second one? I want to avoid using this :
req.session.login ="";
to empty the session variable, Thanks.
The standard way to delete a session variable is to set it to null.
req.session.login = null;
// this also works
delete req.session.login;
The function destroy() is for removing the entire session.

flexible query method/function for MongoDB + Express using NodeJs

I am working on an API with MongoDB+Express+Node.js. So far so good, I can query for one record by ID, I can query for a specific field, delete, add, etc.
I am looking for a method that can be called to create a generic query for mongoDB, where i will pass it a json representation of the model with 'some' data to search for. If the field is not specified in the json object, then it will only search on those fields specified.
Here is the boilerplate code I had, done, but I am very new to JavaScript and Node, and I think i need to parse or sanitize the query object before running the .find method.
Basically I want to be able to perform a query similar to how it is done in parse.com where you send an object model with the data you want to search for and you get all the results that match.
Any help would be greatly appreciated!
--This code is in my custom module--
exports.findByQuery = function(req, res) {
var query = req.query;
db.collection('artists', function(err, collection) {
collection.find(query).toArray(function(err, docs) {
res.send(docs);
});
});
};
--This is the routes file--
var express = require('express'),
artist = require('./routes/artists');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
});
app.get('/search/', artist.findByQuery);
app.get('/artist/:id', artist.findById);
app.post('/artist', artist.addArtist);
app.put('/artist/:id', artist.updateArtist);
app.delete('/artist/:id', artist.deleteArtist);
app.listen(3000);
I just found that the code above DOES work, however you cannot search for _id for some reason.. But any other field would work. Still looking how to incorporate _id in the search.

How can I get the "name" attribute in node.js

<input type='file' name='upload1'/>
When this form is submitted,how can I get the "name" attribute (upload1) on node.js.
I use restify,and upload image.
The right way in node.js is would be to use a web app framework like express. It gives you more options as well as flexibility. In express you can do :
var express = require('express'); //Initialize express
var app = express();
app.listen(3000);
app.use(express.bodyParser()); //to parse the forms
app.post('/pagesubmit', function(request, response){ //to handle POST to the page
console.log(request.body.username); //tp access input text 'username'
console.log(request.files.name); //to access input file 'name'
});
Just use node-formidable for file uploads.

Resources