Why hasOwnProperty returns false? - json

I cant understand why hasOwnProperty return false on the following scenario:
Client side:
<html>
<head>
<script type="text/javascript">
var client = [
{"clientName":"", "clientNickName": ""},
{"clientName":"", "clientNickName": ""},
{"clientName":"", "clientNickName": ""}
];
function onSubmit() {
// update data
client[0].clientName = "AAA";
client[0].clientNickName = "BBB";
client[1].clientName = "CCC";
client[1].clientNickName = "DDD";
client[2].clientName = "EEE";
client[2].clientNickName = "FFF";
// create request
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","~/process_post",true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
// send
xmlhttp.send(JSON.stringify(client));
return true;
}
</script>
</head>
<body >
<form action="http://127.0.0.1:8081/process_post" method="POST">
User Name:
<input type="text" name="userName">
<br>
Nick Name:
<input type="text" name="nickName">
<br>
<input type="submit" value="Submit" onclick="return onSubmit()">
<br>
</form>
</body>
</html>
server side:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(express.static('public'));
app.post('/process_post', function (req, res) {
var x = req.body;
if (x[0].hasOwnProperty('clientName')) {
console.log("yes: clientName exsists");
}
console.log("result: " + req.body);
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I have updated the Q, after get some comments which didnt help.
Why the server does not parse the json data properly ?
The server crash when calling hasOwnProperty on x[0]:
"TypeError: Cannot read property 'hasOwnProperty' of undefined"
Thanks

First thing is that you cannot send an array as a raw object.
You need to send a string representation of it.
Use xmlhttp.send( JSON.stringify(client) );
Then, when you do var x = req.body; you assign the array to the x variable.
So you need to test its items for the property you want and not the array itself.
Try x[0].hasOwnProperty('clientName')

Related

Get Request for RESTful service not working

I'm trying to use a restful service to access data that is posted to a MongoDB cluster. My problem is that I can't even connect to the service, the get request doesn't seem to be working. Console.log("test")is not reached and I'm met with a blank console, so I don't think the readystate is changing.
I've done a ton of troubleshooting and found that the link works on its own (https://RESTfulServiceExample.[REPL.IT USERNAME].repl.co/items) and displays the data when pasted into the search bar. I've also tried changing browsers and even compared to my friend's code which works and STILL I can't even seem to connect.
I'm sure it's just some dumb little mistake but I'm completely at a loss here so any help is MUCH appreciated!
File with get request. I edited out the username. 'item' is the name of the MongoDB cluster.
<html>
<head>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && this.status == 200) {
console.log("test"); //NOT REACHED
var responseObj = JSON.parse
(xhttp.responseText);
};
}
//PROBLEM HERE
xhttp.open("GET", "https://RESTfulServiceExample.[REPL.IT USERNAME].repl.co/items", true);
xhttp.send();
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js">
</script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
RESTful Service:
Index.js: (edited out username and password of mongodb.
var express = require('express'); // control-shift-S to bring up shell in repl.it and npm
install express / other packages
var app = express();
var port = 5000; // the port is automatically routed by the repl.it domain
mongoose = require('mongoose');
Item = require('./model/model.js');
bodyParser = require('body-parser');
mongoose.Promise = global.Promise; // for asynchronous callbacks
mongoose.connect('mongodb+srv://[USERNAME]:[PASSWORD]#cluster0.thmkp.mongodb.net/Pokemon?
retryWrites=true&w=majority');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./routes/routes'); //importing route
routes(app); //register the route
app.listen(port);
Routes.js
'use strict';
module.exports = function(app) {
var itemList = require('../controllers/controller');
app.route('/items')
.get(itemList.list_items)
.post(itemList.create_item);
app.route('/items/:id')
.get(itemList.get_item)
.put(itemList.update_item)
.delete(itemList.delete_item);
};
Try to change
if (this.readyState == 4 && this.status == 200) {
// your code block
}

node.js formidable with express.js

I am new to node.js and learning it from various sources such as bootcamps, websites, etc.
I want to upload a file using formidable module in node.js and express.js framework. Everytime I run this code it show an error....
var oldpath = file.fileupload.path;
^
TypeError: Cannot read property 'path' of undefined
I have used body parser to receive the name of the file.
Node.js code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var formidable = require("formidable");
var fs = require("fs");
var PORT = process.env.PORT || 5000
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.get("/" , function(req, res){
res.render("form");
});
app.post("/fileupload" , function(req, res){
var fileupload = req.body.filetoupload;
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
var oldpath = files.fileupload.path;
var newpath = "C:/Users/ayush/"+files.fileupload.name;
fs.rename(oldpath, newpath, function(err){
if(err)
console.log(err);
else{
res.write("File Uploaded");
res.end();
}
});
});
});
app.listen(PORT, function(){
console.log("Server started");
});
<!DOCTYPE html>
<html>
<head>
<title>FileUpload</title>
</head>
<body>
<form action="/fileupload" method="POST">
<label>
File:
<input type="file" name="filetoupload" enctype="multipart/form-data">
</label>
<button>Submit</button>
</form>
</body>
</html>
I'm new at this too but the form enctype in form.ejs should be in the <form> tag.
Instead of:
<form action="/fileupload" method="POST">
try:
<form action="/fileupload" method="POST" enctype="multipart/form-data">
You should now have your files object.
Cheers,
Mark
This is a complete working example:
upload.js
'use strict';
const fss = require('fs')
const pth = require('path');
const exp = require('express');
const swg = require('swig');
const efm = require("formidable");
const app = exp();
const thm = swg.compileFile(pth.join(__dirname, '', 'upload.html'));
app.listen(9009);
app.get(`/`, async (q, r) => r.send(thm({ msg: "Select a File to Upload" })));
app.get(`/:msg`, async (q, r) => r.send(thm({ msg: q.params.msg })));
app.post('/upload', (r, q) => {
var form = new efm.IncomingForm();
form.parse(r, (e, p, f) => {
let dir = pth.join(__dirname, '', '/media/');
if (!fss.existsSync(dir)) {
fss.mkdirSync(dir);
}
let nPth = dir + f.file.name;
try {
fss.accessSync(nPth, fss.F_OK);
q.redirect("/File Exists");
} catch (file_e) {
let err = fss.renameSync(f.file.path, nPth);
q.redirect(err ? "/Error" : "/File Uploaded");
}
});
});
You can use fss.access for "A-SYNC" operation.
Its better to use "A-SYNC" functions.
upload.html
<h3>{{msg}}</h3>
<br/>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
fileupload object doesn't exist within file, hence you are getting the undefined error.
To access the old path use :
var oldpath = files.upload.filepath;

Return undefined answer from multer

I am using multer in my nodejs application for uploading files. And angularjs for the front end part. Once I click upload image, on the console I am getting undefined answer. Can any one help me to solve the problem.
Here I am pasting the code.
server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
var multer = require('multer');
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/upload/');
},
filename:function(req,file,cb){
cb(null,file.originalname);
}
});
var upload = multer({storage: storage});
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(express.static('public'));
app.get('/',function(req,res){
res.render('index',{ title: 'Upload image' });
});
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
And here is my app.js angularjs code
var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate']);
$scope.img={};
app.controller('Ctrl',function ($scope,$http){
$scope.loadImage = function(){
$http.post('/loadImage',$scope.img).success(function(data){
console.log('Posted successfully');
}).error(function(data){
console.error('error');
})
};
And my HTML code:
<form ng-submit="loadImage()" enctype="multipart/form-data">
<input type="file" name="file" multiple />
<input type="submit" value="Upload Image" name="submit" />
</form>
On the console I am getting Undefined and Inside post. And on the browser console I am getting posted successfully Can any one please help me to solve this. Instead of undefined I should get loaded file information.
This how i used Multer to upload an image
var multer = require('multer');
exports.loadImage = function (req, res) {
var upload = multer({
inMemory: true,
limits: {fileSize: 1024 * 1024 }
}).single('newPicture');
upload(req, res, function (uploadError) {
if (uploadError) {
return res.status(400).send({ message: 'errorUploadingPicture' });
}
else {
var profileImage = 'No data uploaded';
// this is where the photo data is
if (req.file && req.file.buffer) {
profileImage = req.file.buffer;
}
return res.json(profileImage );
}
});
};
This is all assuming you are sending your file correct
try
var uploadType = upload.any()
and change
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
to
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});
if you are attempting to only get one file at a time then instead,
var uploadType = upload.single('file')
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});

Not able to print table

I'm sending the table created in node js to the html web page but the table boundary is not getting printed instead some random characters and symbols are getting printed.
the node js code is :
var express = require('express');
var app = express();
var fs = require('fs')
var googlePlaySearch = require('google-play-search');
var prettyjson = require('prettyjson');
app.use(express.static('public'));
var csv = require('csv');
var Table = require('cli-table');
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
});
app.get('/process_get', function (req, res) {
first_name:req.query.first_name
googlePlaySearch.fetch(req.query.first_name, function(err, response) {
var data =
'Category,name\n' +
response.categories + ' ' +
response.name ;
var chars = {
'top': '═', 'top-mid': '╤', 'top-left': '╔', 'top-right': '╗',
'bottom': '═', 'bottom-mid': '╧', 'bottom-left': '╚',
'bottom-right': '╝', 'left': '║', 'left-mid': '╟', 'mid': '─',
'mid-mid': '┼', 'right': '║', 'right-mid': '╢', 'middle': '│'
};
csv().from.string(data).to.array(function(data) {
var
headers = data[0],
values = data.slice(1),
aligns = [null,'right'],
table = new Table({ head: headers, chars: chars, colAligns: aligns })
;
table.push.apply(table, values);
console.log(table.toString());
});
});
});
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
})
and the html code is (index.htm)
<!DOCTYPE html>
<html>
<head>
<title>Package Details</title>
</head>
<body>
<h1><marquee style="color:yellow" >this is a page to find app details.. </marquee></h1>
<center>
<form id="f1" action="/process_get" method="GET">
<h3 style="color:red">Package Name</h3>:<br>
<input type="text" name="first_name"> <br><br>
<input type="submit" value="Submit" style="font-size: 20px">
</form>
</center>
</body>
</html>
Please help me with the code

AJAX request on Node.js server

I am unable to make an AJAX request from my .html page to my node.js server for a JSON file. I've been reading on AJAX requests, but all I am able to make out is how to display the servers responseText.
It would be great if you could help me out, it would be even better if you could link me some tutorials on this, anyway this is what I've got at this moment:
server.js
var express = require('express');
var fs = require('fs');
var app = express();
app.get('/test', function(req, res){
var arr = new Array();
var rd = readline.createInterface({
input: fs.createReadStream('info.json'),
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
arr.push(line);
}).on('close', function(){
res.send(arr);
});
});
app.get('/', function(req, res) {
fs.readFile('test2.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.listen(process.env.PORT || 3000);
test.html
<html>
<head>
<script>
function sendAjax(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4 && xmlHttp.status == 200){
console.log(xmlHttp.responseText);
}
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
}
xmlHttp.open("GET", "/test", true);
xmlHttp.send();
}
</script>
</head>
<body>
<input type="submit" onClick="sendAjax()" value="SendAjax" />
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
</body>
</html>
I know this may not look like much, I've been struggling with this, and the book I have (Node.js in Action) doesn't help me alot. But as I said, what I want is to display the .json info in the browser. Thx for reading
If I understand right, you may replace
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
with
var parsed = JSON.parse(xmlHttp.responseText);
var html = '';
for (var i = 0; i < parsed.length; i++) {
html += '<div>' + parsed[i] + '</div>';
}
document.getElementById("myDiv").innerHTML = html;
You may also try to replace
res.send(arr);
with
res.json(arr);
Update
Or maybe you just forgot to write this line in the beginning of server.js:
var readline = require('readline');