Hi I am developing android application for that I am using request.js by using the below files how to get the json array and by using this json array I can parse the json object then i will use the server response in clent.
Can any help me.
package.json
{
"name": "node-chat",
"version": "0.0.1",
"main": "app.js",
"dependencies": {
"express" : "~4.0.0",
"mysql" : "~2.5.3",
"connect": "~2.14.4",
"request": "2.36.0"
}
}
app.js
/**
* Module dependencies.
*/
var express = require('express');
var connect = require('connect');
var app = express();
var port = process.env.PORT || 8080;
// Configuration
app.use(express.static(__dirname + '/public'));
app.use(connect.logger('dev'));
app.use(connect.json());
app.use(connect.urlencoded());
// Routes
require('./routes/routes.js')(app);
app.listen(port);
console.log('The App runs on port ' + port);
request.js
var request = require('request');
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : '',
database : 'chat',
}
);
connection.connect();
exports.login = function(name,mobno,reg_id,callback) {
var data = {
name : name,
mobno : mobno,
reg_id : reg_id
};
var que = "SELECT * from users WHERE mobno =" + mobno;
var query = connection.query(que, function(err, rows)
{
if(rows.length == 0){
var query = connection.query("INSERT INTO users set ? ",data, function(err, rows)
{
callback({'response':"Sucessfully Registered"});
});
}else {
callback({'response':"User already Registered"});
}
});
}
exports.getuser = function(mobno,callback) {
var query = connection.query("SELECT * from users", function(err, rows)
{
if(rows.length == 0){
callback({'response':"No Users Registered"});
}else {
callback(removeUser(rows, mobno));
}
});
}
exports.removeuser = function(mobno,callback) {
var que = "DELETE FROM users WHERE mobno =" + mobno;
var query = connection.query(que, function(err, rows)
{
if(!err){
callback({'response':"Removed Sucessfully"});
}else{
callback({'response':"Error"});
}
});
}
exports.send = function(fromn,fromu,to,msg,callback) {
var que = "SELECT * from users WHERE mobno =" + to;
var query = connection.query(que, function(err, rows)
{
if(rows.length == 0){
callback({'response':"Failure"});
}else {
var to_id = rows[0].reg_id;
var name = rows[0].name;
request(
{ method: 'POST',
uri: 'https://android.googleapis.com/gcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization':'AIzaSyAnHnfHRvXKyIJaSjdR82QQULccWxN4nWg'
},
body: JSON.stringify({
"registration_ids" : [to_id],
"data" : {
"msg":msg,
"fromu":fromu,
"name":fromn
},
"time_to_live": 108
})
}
, function (error, response, body) {
callback({'response':"Success"});
}
)
}});
}
function removeUser(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i].mobno == val) {
arr.splice(i, 1);
return arr;
break;
}
}
}
Related
The problem is whenever I call
the server.js to save the details I need to pass data from client.js to server.js.But the server is not understanding the data if I pass an array of JSON objects but receiving if it is a single JSON object.
I tried to print the cart_items array in the console, it is undefined.
//my client.js code
var server_url = "http://127.0.0.1:9000";
$(document).ready(function () {
var cart_items = [{
id: '1',
item: 'rice',
cost: 25
}, {
id: '2',
item: 'roti',
cost: 35
}, {
id: '3',
item: 'curry',
cost: 40
}]
cart_items = JSON.stringify(cart_items);
var menu_item = ['rice', 'roti', 'curry'];
// $("body").append($newdiv1, [newdiv2, existingdiv1]);
console.log(cart_items)
for (let i = 0; i < 3; i++) {
console.log("jadsnkjn")
var $newInput = document.createElement("input");
$newInput.setAttribute('type', 'checkbox')
$newInput.setAttribute('class', 'optionIn')
$newInput.setAttribute('id', 'item' + i)
var $newLabel = document.createElement("label");
$newLabel.setAttribute('for', 'item' + i);
$('#item' + i).text(menu_item[0]);
$(".first_row").append($newInput, $newLabel);
}
$('.proceed_btn').on('click', function () {
$.ajax({
url: server_url + "/save",
type: "POST",
data: cart_items,
success: function (msg) {
alert("Local success callback.fggdfg" + msg);
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
}
})
})
})
----------
//my server.js code
var express = require('express')
var bodyParser = require('body-parser')
var server = express();
var cors = require('cors');
var mysql = require('mysql');
var port = 9000;
server.use(cors())
server.use('/scripts', express.static(__dirname + '/scripts'))
server.use('/css', express.static(__dirname + '/css'))
server.use(express.static(__dirname))
server.use(bodyParser.urlencoded({ extended: true }))
server.use(bodyParser.json());
//Saving the cart details in the database table order_details
server.post('/save', function (req, res) {
var error = 0;
var status_code = 200;
var status_message = "callback success";
var cart_items = []
cart_items = req.body;// I think I am missing somethings here I tried with cart_item = req.body.cart_items still undefined
console.log(cart_items[0].id)//giving undefined
//initiating database insertion
//dbInsertion(cart_items);
return res.status(status_code).send(status_message);
})
//inserting the order details in order_details table after successful payment
function dbInsertion(cart_items) {
var connectionObject = dbConnection();
sql = "insert into order_details values ('" + cart_items[0].id + "','" + 908089 + "')";
connectionObject.query(sql, function (err, result) {
if (err) {
error = error + 1;
status_code = 404;
error_message = "Sorry data could not be entered something is wrong in the sql query syntax";
console.log("error in the sql query" + status_code)
}
else console.log("1 row inserted");
})
connectionObject.end();
}
//establishing the connection with database
function dbConnection() {
var con =
mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "tempdb"
})
con.connect(function (err) {
if (err) throw err;
console.log("connected!")
})
return con;
}
server.listen(port, function () {
console.log("listening at" + port);
})
----------
// this is my index.html page
<html>
<head>
<title>
Eatback
</title>
</head>
<body>
<input type="text" id="key" name="key">
<input type="text" id="value" name="value">
<button id="button" class="btn btn-success">submit</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="scripts/client.js"></script>
<div id="new">
</div>
</body>
</html>
Your code is fine, you only need to remove this line:
cart_items = JSON.stringify(cart_items);
And send your data as object:
data: { cart_items: cart_items },
There is no need to transform the submitted data into json string, if you do so you should parse it to object in the server:
var cart_items = JSON.parse(req.body);
the answer is , in the ajax call data segment it should be data:{cart_items:cart_items} instead of data:cart_items
My code is as shown below:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');
var user = require('./../model/user');
var path = require('path');
var upload = multer();
var awsUpload = require('./../config/fileUpload.js');
var Promise = require('promise');
var item = require('./../model/items.js');
var item_image = '';
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './public/images')
},
filename: function(req, file, callback) {
item_image = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
callback(null, item_image)
}
});
var itemAdd = function(req, res) {
upload = multer({
limits: {
fileSize: 1000000,
files: 1
},
storage: storage,
fileFilter: function(req, file, callback) {
var ext = path.extname(file.originalname)
if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
return callback(res.end('Only images are allowed'), null)
}
callback(null, true);
}
}).single('item_img');
upload(req, res, function(err) {
var foodtruck_id = req.body.foodtruck_id;
var newItem = new item();
var itemList = [];
newItem.item_name = req.body.item_name;
newItem.item_tag = req.body.item_tag;
newItem.item_description = req.body.item_description;
newItem.item_category = req.body.item_category;
newItem.item_discount_price = req.body.item_discount_price;
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
if (key == 'item_illustrations') {
newItem.item_illustrations = req.body[key];
}
}
}
newItem.item_stock = req.body.item_status;
newItem.item_price = req.body.item_price;
if ((foodtruck_id) && (foodtruck_id.trim() != '')) {
foodtruck.findById(foodtruck_id.trim(), function(err, foodtrucks) {
if (err)
res.json({
status: '500',
message: 'There is no data available'
});
newItem.save(function(err, savedItem) {
if (!err) {
foodtrucks.item_list.push(savedItem._id);
foodtrucks.save(function(err, truck) {
foodtruck.find({
_id: truck._id
}).populate('item_list').exec(function(err, foodtrucks) {
res.json({
status: '200',
message: 'New item added successfully',
data: foodtrucks
});
});
});
} else {
res.json({
status: '500',
message: 'Error while saving new item'
});
}
});
});
}
});
};
app.js
app.post('/test',itemAddition);
Now what happens here is, when I use req.body.hasOwnProperty with x-www-formurlencoded, it works fine, but whenever I am adding it with multer (multipart-data), it gives me req.body.hasOwnProperty is not a function. Is there any way with which this thing can be solved?
req.body is a prototype-less object: it was created with Object.create(null) and so doesn’t inherit hasOwnProperty from Object.prototype. This is a good thing, because if a user passed a field named hasOwnProperty, they would be able to break your code.
Use the in operator instead, generally:
if (key in req.body) {
But in the case of the loop, you just don’t need a check at all:
for (var key in req.body) {
if (key == 'item_illustrations') {
newItem.item_illustrations = req.body[key];
}
}
And in this particular case, just get the value you want without a loop at all:
newItem.item_illustrations = req.body.item_illustrations;
Sorry for my bad english.
I have a problem. I need to create, for all object in my mongoDB, a delete button for each object.
I use mongodb, Nodejs, ajax and jquery.
This is my mongodb code :
{
"_id" : ObjectId("57ce990ac4e8ec94124a1c2c"),
"Pseudo" : "shade",
"Commentaire" : "blabla",
"Note" : "2",
"Date" : ISODate("2016-09-06T10:22:53.257Z")
}
{
"_id" : ObjectId("57cebf1c12253ee41e0aa53e"),
"Pseudo" : "shade2",
"Commentaire" : "blablaalalalallala",
"Note" : "5",
"Date" : ISODate("2016-09-06T13:00:10.871Z")
}
{
"_id" : ObjectId("57d7b7b909087b981124bc42"),
"Pseudo" : "shade3",
"Commentaire" : "hfsduhfdiugfusqdigfqgfugsufgsfqd",
"Note" : "1",
"Date" : ISODate("2016-09-13T07:45:24.970Z")
}
My node code :
var express = require('express');
var bodyParser = require("body-parser");
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://127.0.0.1:27017/jeux';
var myDate = new Date;
app.use(express.static(__dirname + '/fichiers'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/fichiers'))
app.get('/', function (req, res) {
res.render('index.html');
})
app.get('/api/affiche', function (req,res){
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
db.collection('temp').find().toArray(function (err, result) {
if (err) {
throw err;
} else {
res.json(result);
}
});
}
});
})
var server = app.listen(8080, function () {
var adressHost = server.address().address;
var portHost = server.address().port;
console.log('Ecoute à l\'adresse http://%s:%s', adressHost, portHost);
});
My jade code
doctype html(lang='fr')
head
meta(charset='utf-8')
script(type='text/javascript', src='jquery.js')
script(type='text/javascript', src='admin.js')
link(rel='stylesheet', href='admin.css')
body
h1 Page d'admin
.listeAvis
And my jquery/ajax code
$(function () {
$.ajax({
type: 'GET',
url: '/api/affiche',
success: function (data) {
$('.liste').html('<h2>Nouveaux avis</h2>');
for (var i = 0; i < data.length; i++) {
//var i = 0;
$('.listeAvis').append('<p>pseudo : ' + data[i].Pseudo + '</p>');
$('.listeAvis').append('<p>commentaire : ' + data[i].Commentaire + '</p>');
$('.listeAvis').append('<p>note : ' + data[i].Note + '</p>');
$('.listeAvis').append('<p>-----------------------------</p>');
$('.listeAvis').append('<br></br>');
}
}
})
})
I thought but I can not find how to do. Please help me :(
I'm wondering why req.session.username is undefined in the tag >>>DOESNT WORK<<< while it does work in the tag >>>THIS DOES WORK<<< . I brought in req as an argument to my module but it seems I'm supposed to do something else? The /ajax route is accessed via a ajax call and it does set the session variable in >>>THIS DOES WORK<<<
//index.js file
var express = require('express');
var router = express.Router();
var app = express();
var functions = require('../public/javascripts/functions.js');
router.post('/ajax', function(req, res , next){
var username = req.param("username");
var password = req.param("password");
var operation = req.param("operation");
else if (operation === "validate")
{
async.series([
function()
{
functions.validate(username, password, req);
}
], function(err,result)
{
if (err)
return console.log(err);
console.log(result);
});
//req.session.username = "yaryar"; >>>THIS DOES WORK<<<
}
var strings = ["rad", "bla", "ska"]
console.log('body: ' + JSON.stringify(req.body));
console.log("AJAX RECEIVED");
res.send(strings);
});
module.exports = router;
functions.js file:
module.exports = {
validate: function(username, password, req) {
var url = 'mongodb://localhost';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
MongoClient.connect(url, function(err, db)
{
assert.equal(null, err);
console.log("Connected correctly to server.");
var cursor = db.collection('users').find({username : username});
cursor.each(function(err,doc,req)
{
assert.equal(err, null);
if (doc != null)
{
console.log("user found: " + doc.username);
req.session.username = "ttyy"; // >>>DOESNT WORK<<<
return true
}
else
{
console.log("user not found");
return false;
}
});
//db.close();
});
}
};
you're overwriting req by doing cursor.each(function(err,doc,req) change it to cursor.each(function(err,doc,arr) and it will work
My node.js app aim to scan a list of website an return in a panel, statusCode, and other tests.
Now the app work like that :
The page is empty until the end of the load and if one website in the list is slow the loading is slow, when 100% of the websites are scan the panel show.
How can i show the panel when i load the page, and show other informations progressively ?
var express = require('express');
var fs = require('fs');
var http = require('http');
var ejs = require('ejs');
var async = require('async');
var request = require('request');
var app = express();
var mysql = require('mysql');
var cheerio = require('cheerio');
app.use(express.static(__dirname+"/public"));
// Database connection
app.get('/', function(req, res) {
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'app'
});
connection.connect();
var jsons = new Array();
var odbc;
connection.query('SELECT * from websites', function(err, rows) {
if (err) throw err;
async.each(rows, function(row, callback) {
http.get(row.url, function(resp) {
row.status = resp.statusCode;
request(row.url, function(error, response, html){
if(!error){
var $ = cheerio.load(html);
str = $('*').text();
var errorODBC = str.indexOf("function.odbc-connect");
var errorTrans = str.indexOf(".WDD");
if(errorODBC != '-1'){
row.odbc = 'Erreur odbc';
}
if(errorTrans != '-1'){
row.aw = 'Erreur transfert';
}
jsons.push(row);
callback();
}
});
}).on('error', function(e) {
console.log("Erreur : " + e.message);
});
},function(){
res.render('index.ejs', {data : jsons});
console.log("Scan done...");
});
});
connection.end();
});
app.listen(8080);