I'm using Node.js and I'm having issues communicating with a client.
I define Express:
var express = require("express");
var app = express();`
When I try and pass a parameter to the client upon requesting a page the variable holds no data, for example:
app.get("/", function(req, res){
res.render("index", { name: "example" });
});
On the index page, when I use the console to print the variable (name)it returns "".
More info: http://expressjs.com/api.html#app.render
Am I missing something or doing something wrong?
The variable name you sent to the render function is only available while rendering the page, after it is sent to the client, it is not accessible. You have to use it in your view on the rendering stage.
Since you are using handlebars, you can display it in your page like this, for instance:
<h1>{{ name }}</h1>
If you want to use this data in a javascript, use it inside a script tag:
<script>
var name = "{{ name }}";
console.log(name);
</script>
You are basically telling express to render your index page and providing a value for the name variable, but that doesn't necessarily make the name var available in your client side javascript. You need to edit your index template to display the name variable in the page.
The syntax varies depending on the templating engine you are using (jade, ejs, dustjs).
Another solution is to use an ajax call in your client page's javascript and use res.json on the server instead to send the data. Then you can evaluate name in the console. Ex using jquery:
index.html:
$.get( "/getvar", function( data ) {
name = data.name;
});
server.js:
app.get("/getvar", function(req, res){
res.json({ name: "example" });
});
If you want to get parameters on the clientside via javascript, you should do template like this <script>var data = data</script>, otherwise variables aren't available
If you use Jade, it will be something like this:
script(type='text/javascript').
var name = !{name}
Passing data list from node js to html
server.js
var http = require('http');
var express = require('express');
var sqlite3 = require('sqlite3').verbose();
var bodyParser = require('body-parser');
var path = require("path");
console.log('Server running at http://127.0.0.1:8081/');
var __dirname = "D:/html-files";
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var engine = require('consolidate');
app.engine('html', engine.mustache);
app.use(express.static('./'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
});
app.post('/get-user-list', urlencodedParser, function (req, res) {
let db = new sqlite3.Database('user.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the user database.');
console.log("ID" + "\t" + "NAME" + "\t" + "EMAIL");
});
db.serialize(() => {
var dataList = "";
db.each('SELECT id, name, email FROM USER ', (err, row) => {
if (err) {
console.error(err.message);
}
if(dataList != "")
dataList = dataList + ',';
dataList = dataList + '{"id":"' + row.ID + '","name":"' + row.NAME + '","email":"' + row.EMAIL + '"}';
console.log("dataList : " + dataList);
});
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Close the database connection.');
response = {'username':dataList};
aFunction(res, dataList);
});
});
});
var aFunction = function(res, dataList) {
console.log('return to page.');
console.log("dataList : " + dataList);
res.render(__dirname + "/list-all-users.html", response);
};
app.listen(8081, '127.0.0.1')
Related
Basically, the below put service that should execute a simple Redis-cli> SET KEY VALUE can't work.
The get operations work well.
Using separately the redis module and calling the set function also works.
But when called from app.put() the KEY/VALUE pair isn't registered.
What's the hell???
// express setup
const REDIS_REST_PORT = 3000;
const express = require('express');
const router = express.Router();
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// redis setup
const REDIS_CONNECTION_STRING = "redis://127.0.0.1:6379";
const RedisCli = require('redis').createClient(REDIS_CONNECTION_STRING);
RedisCli.on('connect', function() {
console.log('Connected to REDIS');
});
RedisCli.on('error', function(err) {
console.log('/!\ REDIS ERROR: ' + err);
});
// GET .../get/KEY (works well !!)
app.get('/get/:key', function(req, res) {
RedisCli.get( req.params.key, function (err, result) {
if (err) {
res.send(err,500);
} else {
res.send(result);
}
});
});
// PUT .../set/KEY + body (can't work KEY/VALUE never registered ??)
app.put('/set/:key', function(req, res) {
var value = "'" + JSON.stringify(req.body) + "'";
console.log("SET " + req.params.key + " " + value);
RedisCli.set( req.params.key, value,
function (err, result) {
if (err) {
res.send(err,500);
} else {
res.send(result);
}
});
});
// Start REST server
app.listen(REDIS_REST_PORT, () =>
console.log('Listening on port '+ REDIS_REST_PORT + '...'));
Eventually it used to work - don't understand how and why - see my comment.
I am working on a personal project and I do not have much experience with nodeJS, the idea is to bring a JSON that has remotely taken some data and generate some statistics, I am doing some tests before starting fully in the project and I am having problems with the callback.
the server.js works correctly,
my module is the following:
const extjson = require('remote-json');
//---------------------API CONFIG--------------------------
//apikey
const apikey ="xxxxxxxxxxxxxxxxxxxxx";
function get_sum_id(sumname){
const urlsumbySumName = "https://la2.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + sumname + "?api_key=" + apikey;
var id;
extjson(urlsumbySumName).get((err, res, body)=> {
id = body.id;
});
return id;
}
module.exports = {get_sum_id
};
and the routes.js is the following:
const riot = require('./rapi.js');
const express = require('express');
//---------------------------------------------------------
const router = express.Router();
//Jtask -- task remote json
//const Task = require('../models/Task'); // taskdb
router.get('/',async (req, res) => {
res.render('index');
});
router.post('/profile', (req,res)=>{
const sum = req.body.summoners;
console.log(riot.get_sum_id(sum));
res.render('profile',{sum});
});
module.exports = router;
I want to show that id by console and it returns undefined, the idea is to pass that value to the render below to have it available in an EJS document.
Your module make an asynchronous call to another server with remote-json. It means that the callback will be called only after the request to this other server. So, this line return id; is read before this line id = body.id;.
One way to fix that is to provide the callback from the place where you call your module function.
Based on your code you could do something like that :
// module.js
const extjson = require('remote-json');
const apikey ="xxxxxxxxxxxxxxxxxxxxx";
function get_sum_id (sumname, callback) {
const urlsumbySumName = "https://la2.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + sumname + "?api_key=" + apikey;
extjson(urlsumbySumName).get(callback);
}
module.exports = { get_sum_id };
// app.js
const riot = require('./rapi.js');
const router = express.Router();
router.post('/profile', function(req, res, next) {
riot.get_sum_id(req.body.summoners, function (err, resp, body) {
console.log(body);
res.json(body); // Response here
});
});
module.exports = router;
Now, requests to your server will be in pending until your callback close it with res.json(body);.
Thank you very much I am working, now I understand much better how the asynchronous functions work. I leave here the complete solution to my problem in case someone needs it in the future:
//rapi.js
const extjson = require ('remote-json');
//---------------------API CONFIG--------------------------
//apikey
const apikey ="RGAPI-77f658f1-ff2b-40e7-a74c-47f7510c8dac";
//trayendo los datos desde riot
function get_sum_id(sumname, callback){
const urlsumbySumName = "https://la2.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + sumname + "?api_key=" + apikey;
extjson(urlsumbySumName).get(callback)
}
module.exports = { get_sum_id };
//routesapp.js
const riot = require('./rapi.js');
const express = require('express');
//---------------------------------------------------------
const router = express.Router();
router.get('/',async (req, res) => {
res.render('index');
});
router.post('/profile', (req, res, next)=>{
const sum = req.body.summoners;
riot.get_sum_id(sum,function (err, resp, body){
console.log(body.id);
//responces....
res.render('profile',{sum, id: body.id})
});
});
module.exports = router;
TNX very much!
I'm trying to write/add data in a json file (for example for each request, a new json is added in the json file) i am using Express.js. I am new to all of this so I really don't know what to do. I'm using a POST request, here's what i got so far. I know it's a big catastrophic mess, i scraped everything that could help me and gathered all of it. I'm just SO lost. Thanks for your help !
app.post('*/', function(req, res) {
res={
first_name: req.body.first_name,
last_name: req.body.last_name,
reponse1: req.body.reponse1,
reponse2: req.body.reponse2,
};
JSON.stringify(res);
var body = {
table: []
};
body.table.push(res);
filePath = __dirname + '/data.json';
req.on('data', function(data) {
body += data;
});
req.on('end', function (){
fs.appendFile(filePath, body, function() {
res.end();
});
});
});
In your code, I see a lot of bugs. Firstly, you should not assign res = { }. Secondly, you stringify the JSON data like below. I will also suggest you to go through some tutorials of Node.js first. You can go through https://www.tutorialspoint.com/nodejs/ or https://www.codementor.io/nodejs/tutorial.
For your requirement, you can simply use following code:
const express = require('express')
const app = express()
const bodyParser= require('body-parser')
const fs = require('fs')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/', function(req, res){
var body = {
first_name: req.body.firstName,
last_name: req.body.lastName
}
filePath = __dirname + '/data.json'
fs.appendFile(filePath, JSON.stringify(body), function(err) {
if (err) { throw err }
res.status(200).json({
message: "File successfully written"
})
})
})
app.listen(3000,function(){
console.log("Working on port 3000")
})
Like the title entails.
I'm trying to make an application that when i put in certain info, it creates a link using mongoose _id. and express's app.get what i don't get is that to be able to join that directory i have to reload the whole server, which for the users and my sake a i don't want to do.
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var router = express.Router();
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
name: {
type: String,
unique: false
}
});
var collectionOfData = mongoose.model("dataType", collectedData);
io.on("connection", function (socket) {
socket.on("name", function (e) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
var Maindata = new collectionOfData({
ipAddress: ip,
name: e
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
});
app.get("/mix", function (req, res) {
collectionOfData.find(function (err, data) {
res.send(data);
});
});
collectionOfData.find(function (err, data) {
data.forEach(function (uniqueURL) {
app.get("/" + uniqueURL._id, function (req, res) {
res.send("<h1>Hello " + uniqueURL.ipAddress + "</h1><p>" + uniqueURL.name + "</p>");
});
});
});
http.listen(10203, function () {
console.log("Server is up");
});
So what i'm trying to do is make it so i don't have to reload the whole server, and i'm able to just join the created directory when it's done being loaded.
figured i should put a quick example:
localhost:10203/55c2b2f39e09aeed245f2996
is a link a user just created the long
55c2b2f39e09aeed245f2996
is the effect of the _id, but when the user try's to connect to that site it won't work until i reload the server and obviously i'd like to avoid that haha.
I have a index.html file, but all that has is a socket.emit that sends "name" to the server
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
app.get('/:uniqueURL', function(req, res){
var id = req.params.uniqueURL;
res.send("Your requested id : " + id);
})
Try to use this above.
You are creating fix get path inside collectionData.find. That is the problem. So each time you have to reload the server by restarting.
I have an iOS app which is sending a JSON packet to a webserver. The webserver code looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("MongoDB connection is open.");
});
// Mongoose Schema definition
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
X: Number,
Y: Number,
Orientation: Number,
UserID: String,
Time: String
});
// Mongoose Model definition
var LocationsCollection = mongoose.model('locations', LocationSchema);
// create application/json parser
var jsonParser = bodyParser.json();
// URL management
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
console.log(req.body);
}
});
// Start the server
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('App listening at %s:%s',host, port)
});
The key part is the app.post method which processes the incoming http request being sent from my iOS app. At the moment, the method which prints the req.body to the console looks like this:
{
datapoint_1:
{ timestamp: '2015-02-06T13:02:40:361Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 271.3345946652066 },
datapoint_2:
{ timestamp: '2015-02-06T13:02:40:961Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 273.6719055175781 }
}
So, you can see the request is a nested JSON object. Ideally, I'd like to loop through the request objects (ie. the datapoints) and insert those into the mongoDB database (via mongoose). However, I can't seem to figure out how to do much of anything with the req.body. I can't seem to create a loop to iterate through the request or how to properly parse the nested JSON file so it matches the mongoose schema. Can anyone provide some guidance on how to insert these datapoints into the mongoose database?
Set body-parser's extended property to true to allow parsing nested objects.
var express = require('express');
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
Answering my own question. But, after figuring out how to access the key/value pairs inside the nested JSON object... it became relatively easy to figure out the rest. The updated app.post function now looks like this:
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
for(var datapoint in req.body){
//create new instance of LocationCollection document
var point = new LocationsCollection({
X:Number(req.body[datapoint]["x"]),
Y:Number(req.body[datapoint]["y"]),
Orientation:Number(req.body[datapoint]["orientation"]),
Time:req.body[datapoint]["timestamp"],
UserID:req.body[datapoint]["id"]
});
//insert the newly constructed document into the database
point.save(function(err, point){
if(err) return console.error(err);
else console.dir(point);
});
}
}
});
I can test if this worked by putting the following method inside the callback function once the mongodb connection is first established:
//Find all location points and print to the console.
console.log("Searching for all documents in Location Points Collection");
LocationsCollection.find(function(err,data){
if(err) console.error(err);
else console.dir(data);
});
This will print any documents that have been previously added to the database. Hopefully this helps.
Try somthing like this.
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit:1024*1024, verify: function(req, res, buf){
try {
JSON.parse(buf);
} catch(e) {
res.send({
error: 'BROKEN_JSON'
});
}
}}));
It should be a simple for (var key in obj) loop:
app.post('/update', jsonParser, function (req, res) {
var locationObject = req.body(),
insertObjects = [],
key;
for (key in locationObject) { // loop through each object and insert them into our array of object to insert.
insertObjects.push(locationObject[key]);
}
if (!insertObjects.length) { // if we don't have any object to insert we still return a 200, we just don't insert anything.
return res.status(200).send({
success: true,
message: 'Nothing inserted, 0 locations in POST body',
count: 0;
});
}
LocationsCollection.create(insertObjects, function (err, res) {
if (err) {
return res.status(400).send({
success: false,
message: err.message
});
}
// we have successfully inserted our objects. let's tell the client.
res.status(200).send({
success: true,
message: 'successfully inserted locations',
count: insertObjects.length;
});
});
});
Mongo allows for inserting multiple documents with a single callback, which makes this a lot easier.
This also checks the schema to ensure only proper documents are created.