How to validate a data insert with mongoDB - javascript

how can i validate after data insert and saving data to database if data already in a database send user to error alert message.
how can i do this with express REST server?
this is my "POST" on client side
button.addEventListener('click', function(e) {
var service_ = service.value;
var amount_ = amount.value;
var name_ = name.value;
var phone_ = phone.value;
var reminder_ = reminder.value;
if (start_pick < end_pick) {
var jsondata = [{
start_time : new Date(start_pick),
end_time : new Date(end_pick),
service : service_,
amount : amount_,
client_phone : phone_,
client_name : name_,
reminder : reminder_
}];
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(10000);
xhr.open("POST", "http://127.0.0.1:3000/collections/appoinments");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(jsondata));
xhr.onerror = function() {
Titanium.API.info("Error in connecting to server !!");
alert("Error on connecting to server, Please try again");
};
xhr.onload = function() {
windowPayment.close();
}
this is my POST on server
app.post('/collections/:collectionName', function(req, res, next) {
req.collection.insert(req.body, {}, function(e, results){
if (e) return next(e)
res.send(results)
})
})
how can i do this.any help?

Related

using SFTP in JSCH to upload files,I want to know how to display the progress about uploading files

my web page have a button to select the files,when the button clicked,it will send files data to webserver,then webserver will build a SFTP service which is built from JSCH,then the files will be sent to remote server.now I want to know how to develop the progress bar.I have already developed the progress bar when files send to web server.I try to develop the progress bar when files send to remote server but i failed. enter image description here
picture one is the process which sends files to webserver.
picture two is the process which sends files to remote server.
enter image description here
// here is code which sends files to webserver.
$(function() {
$('#inputButton').on('click', function() {
var fd = new FormData();
var files_upload_num = document.getElementById('fileToUpload').files.length;
if(files_upload_num == 0)
{
alert('请选择文件,完成上传!');
return;
}
for(let i=0;i<files_upload_num;i++)
fd.append("fileToUpload", document.getElementById('fileToUpload').files[i]);
$.ajax({
url: '<%=path%>/FileCl?method=submitFile',
type: 'post',
data: fd,
processData: false,
contentType: false,
xhr: function() {
var newxhr;
if (window.XMLHttpRequest) {
newxhr = new XMLHttpRequest();
} else {
// code for IE6, IE5
newxhr = new ActiveXObject("Microsoft.XMLHTTP");
}
newxhr.upload.onprogress = function(e) {
console.log(e)
var percent = ( (e.loaded / e.total).toFixed(2) ) * 100 + '%'
$('#progressBar').css('width', percent)
document.getElementById('progressBar').innerHTML = percent;
}
newxhr.addEventListener("load", uploadComplete, false);
newxhr.addEventListener("error", uploadFailed, false);
newxhr.addEventListener("abort", uploadCanceled, false);
return newxhr
},
success: function(res) {
console.log(res)
},
dataType: 'json'
})
})
})
//here is code which sends files to remote server.
JSch jSch = new JSch();
Session jSchSession = null;
ChannelSftp chSftp = null;
jSchSession = jSch.getSession(username, host, port);
jSchSession.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
jSchSession.setConfig(config);
jSchSession.setTimeout(1000*10);
jSchSession.connect();
chSftp = (ChannelSftp)jSchSession.openChannel("sftp");
chSftp.connect();
chSftp.setFilenameEncoding("UTF-8");
sftpUtil sftpUtil = new sftpUtil(chSftp);
for (FileItem item : fileItemList) {
String filename = item.getName();
if (filename == null || filename.trim().equals("")) {
continue;
}
String id = UUID.randomUUID().toString().replace("-","");
id = id.substring(0,8);
File saveFile = new File(path,id+filename);
fileNameList.add(id+filename);
sftpUtil.upload("/home/liuyb/uploads",filename,item.getInputStream(),new uploadFileProgressMonitor(item.getSize()));
}

Change name of card on Trello with API by Javascript

I have this code in Javascript to modify the name of a Trello card through its API, and I do not get it, any ideas?
Documentation API Trello: https://developers.trello.com/v1.0/reference#cardsid-1
Code:
var onAuthorize = function() {
updateLoggedIn();
$("#output").empty();
Trello.members.get("me", function(member){
$("#fullName").text(member.fullName);
var id= "5ab7c3c631a2019c50b701c8";
//Change name
Trello.put('/boards/me/cards/5ab7c3c631a2019c50b701c8/name?value=nombrecito',function () {alert("funciona bien")}, function(err) {alert( "mal")});
});
};
var updateLoggedIn = function() {
var isLoggedIn = Trello.authorized();
$("#loggedout").toggle(!isLoggedIn);
$("#loggedin").toggle(isLoggedIn);
};
var logout = function() {
Trello.deauthorize();
updateLoggedIn();
};
Trello.authorize({
interactive:false,
success: onAuthorize
});
$("#connectLink")
.click(function(){
Trello.authorize({
type: "popup",
success: onAuthorize
})
});
$("#disconnect").click(logout);
The error I get is [object Object]
I have also tried with this URL:'cards/5ab7c3c631a2019c50b701c8/name?value=nombrecito'
It looks like your Trello.put URL is a little off.
Fix the Trello.put with...
Trello.put("/boards/mecards/5ab7c3c631a2019c50b701c8/name?value=nombrecito", function () {}, function(err) {alert(err)});
Have you tried the live example on the documentation page? It's not that complicated and something like this.
const API_KEY = 'your key';
const TOKEN = 'your token';
let id = 'your trello card id';
let newName = 'a new name what you want';
var data = null;
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("PUT", "https://api.trello.com/1/cards/"+id+"?name="+newName+"&key="+API_KEY+"&token="+TOKEN);
xhr.send(data);
I've tested with my own cards and it works very well.

Response.write() or .toString() (bug?) on NodeJS server

I am a trying to make a small web server for testing. I made it with NodeJS. But something unexpected happened. The webpage passed by the NodeJS server couldn't be displayed properly. But the webpage worked perfectly when I used php+Apache. When I opened the source code received at my client side, there are no observable difference. Here is my code:
Server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var Max = 30;
var port = process.argv[2];
var server = http.createServer( function (request, response) {
var pathname = url.parse(request.url).pathname; if (pathname == "") pathname = "index.html";
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(port);
console.log('Server running at http://127.0.0.1:8081/');
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
socket.on('close', function () {
console.log('socket', socketId, 'closed');
delete sockets[socketId];
});
socket.setTimeout(4000);
});
function anyOpen(array) {
for (var ele in array) {
if (ele) return true;
}
return false;
}
(function countDown (counter) {
console.log(counter);
if (anyOpen(sockets)) {
return setTimeout(countDown, 1000, Max);
} else if (counter > 0 ) {
return setTimeout(countDown, 1000, counter - 1);
};
server.close(function () { console.log('Server closed!'); });
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
})(Max);
Chatroom2-0.php
<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width:95%;
rows:50;
height:80%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script type="text/javascript">
var str = "";
function enter(e){
if (e.keyCode == 13 && document.getElementById("Input").value) {
//alert("Enter!!!!");
sendInput();
document.getElementById("Input").value = "";
}
};
function updateBoard() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("MsgBoard").innerHTML = xmlhttp.responseText;
}
var textarea = document.getElementById('Output');
textarea.scrollTop = textarea.scrollHeight;
};
xmlhttp.open("POST","Server.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Username&Content="+document.getElementById("Username").value);
};
function sendInput() {
username = document.getElementById("Username").value; if (!username) username = "Gotemptyname";
msg = document.getElementById("Input").value; if (!msg) msg = "GotNothing";
if (msg) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Server.php",true);
//xmlhttp.open("POST","test.txt",true);
//xmlhttp.send();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Message&Username="+username+"&Content="+msg);
//alert(xmlhttp.responseText);
}
};
</script>
</head>
<body onload="setInterval('updateBoard()',1000)">
<div id="MsgBoard"></div>
<form name="UsrInput">
<?php
if (isset($_POST["Username"]))
echo '<input type="text" id ="Username" value="'.$_POST["Username"].'" disable>';
else {
header("Location: /login/index.html");
die();
}
?>
<input type="text" id="Input" onkeypress="enter(event)" value="" >
</form>
</body>
</html>
Users should be able to access the Chatroom2-0.php after login. The login functionality is also ok. But when I entered the Chatroom2-0.php, I got a String, next to my textbox.
'; else { header("Location: /login/index.html"); die(); } ?>
I noticed that the string is part of my php code in the file. I don't know what's happening. I think this might have something to do with the response.write() or the data.toString() function. Maybe the function changed something in my coding? How could I solve this problem.
Anyway, I appreciate for any help given.
The problem is that you are trying to run php code on a nodejs server. There is no solution to this, as node is not a php interpreter, so it sees everything as html text; thus your php code appearing on the page. You need to create an entirely different html for the node project.

How to download a file that I have chosen from Google Picker API?

I am implementing the Google Picker in a PHP site. I am able to get the file id from the Google Picker API and also I can download the file using JavaScript. Following is my callback function called in setCallback(pickerCallback) function.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
document.getElementById('googleFileId').value = fileId;
var name = data.docs[0].name;
var url = data.docs[0].url;
var accessToken = gapi.auth.getToken().access_token;
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/drive/v2/files/' + fileId);
request.setRequestHeader('Authorization', 'Bearer ' + accessToken);
request.addEventListener('load', function() {
var item = JSON.parse(request.responseText);
window.open(item.webContentLink,"_self"); //Download file in Client Side
});
request.send();
}
var message = 'File ID of choosen file : ' + fileId;
document.getElementById('result').innerHTML = message;
}
I can pass the file id to PHP, but to download the file I have to authenticate again. Can any one help in how to proceed with file download in PHP ?
There is a Manage Downloads help in Google Developers page but it is not working for me https://developers.google.com/drive/web/manage-downloads.
Found a question similar to this one but no answers to how to download the file in backend Download file right after picked file from google picker.
You have to implement a callback for the pick action. Take a look at my implementation:
var buildPicker = function(parentId) {
var pickerCallback = function(data) {
if (data[google.picker.Response.ACTION] === google.picker.Action.PICKED && data.viewToken[0] !== 'upload') {
var docs = data[google.picker.Response.DOCUMENTS];
for (var d = 0; d < docs.length; d++) {
downloadFile(docs[d].id);
}
}
};
GAuth.getToken().then(function(token) {
var picker = new $window.google.picker.PickerBuilder()
.addView(new google.picker.DocsUploadView().setParent(parentId))
.addView(new google.picker.DocsView().setParent(parentId).setIncludeFolders(true))
.setDeveloperKey(apiKey)
.setOAuthToken(token.access_token)
.setCallback(pickerCallback);
picker.enableFeature(google.picker.Feature.MULTISELECT_ENABLED);
picker.build().setVisible(true);
});
};
var downloadFile = function(fileId) {
getFile(fileId).then(function(file) {
var downloadUrl;
if (angular.isDefined(file.exportLinks)) {
downloadUrl = file.exportLinks['application/pdf'];
} else {
downloadUrl = file.webContentLink;
}
var $idown;
var makeiFrame = function(url) {
if ($idown) {
$idown.attr('src', url);
} else {
$idown = $('<iframe>', {
id: 'idown',
src: url
}).hide().appendTo('body');
}
};
makeiFrame(downloadUrl);
});
};
// Implemented with https://github.com/maximepvrt/angular-google-gapi. But any other implementation will be fine as well
var getFile = function(fileId) {
var parameters = {
'fileId': fileId
};
return GApi.executeAuth('drive', 'files.get', parameters);
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Get LinkedIn Access Token with OAuthSimple in Javascript

I'm using OAuthSimple in Javascript with PIN based authentication (OOB flow).
We are developing an HTML5 app which lives inside a mobile device's native wrapper using PhoneGap. There's not ANY server side (no URL at all), all requests are sent using the mobile device as a proxy.
So far I managed to:
- Get Request Token
- Redirect user to authorization page
- Got authorization PIN
I need sample code that shows how to get an Access Token using OAuthSimple Javascript library.
Any help will be appreciated. Thanks!
Not sure if you are the same person who posted on our forums recently (see post here https://developer.linkedin.com/forum/oauthsimple-request-access-token), but I replied with demo code on how to do just that using OAuthSimple.
The actual sample code can be found here: https://gist.github.com/efc88a38da25ff4e9283
If you need any help using it, don't hesitate to reach out!
-Jeremy
This will create a phonegap linkedIn login, its just a worked around code though, but this works atleast for me
var consumer_key = "key";
var shared_secret = "secrete";
self.oauth = OAuthSimple(consumer_key, shared_secret); var linkedInScope = 'r_basicprofile r_emailaddress w_messages r_network';
var url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/requestToken", parameters: {scope: linkedInScope, oauth_callback: "oob"}}).signed_url;
var request = 'requestToken';
var linkedInObj = new Object;
function linkedInWorkAround(url,request,data){
var callType = 'GET';
var xhr = $.ajax({
url : url,
beforeSend : function(){
$.mobile.loading( 'show' );
if(request == 'linkedIn_login'){
callType = 'POST';
}
},
timeout : 8000,
data : data,
type : callType,
success: function(r){
$.mobile.loading( 'hide' );
if(request == 'requestToken'){
var oauthRes = r.split('&');
$.each(oauthRes, function(k,v){
var resObj = v.split('=')
linkedInObj[resObj[0]] = resObj[1];
});
url = 'https://www.linkedin.com/uas/oauth/authenticate?scope='+linkedInScope+'&oauth_token='+linkedInObj.oauth_token;
request = 'oauth_token';
linkedInWorkAround(url,request);
}
else if(request == 'oauth_token'){
var accessCode = $(r).find('.access-code');
if(accessCode.size()){
self.oauth.reset();
var pin = $(r).find('.access-code').text();
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {scope: linkedInScope, oauth_verifier: pin}, signatures: linkedInObj}).signed_url;
request = 'accessToken';
linkedInWorkAround(url,request);
}
else{
$('.custom-linkedIn').remove();
var cloneIn = $(r).find('form').addClass('custom-linkedIn').clone();
$('a,span,select,.duration-label,.access',cloneIn).hide();
$('#pageLinkedIn .errMsgHolder').after(cloneIn)
$('#session_key-oauthAuthorizeForm').textinput();
$('#session_password-oauthAuthorizeForm').textinput();
$('input[type=submit]').button();
$('form.custom-linkedIn').submit(function(){
$('.errMsgHolder').hide().text('');
url = 'https://www.linkedin.com/uas/oauth/authorize/submit';
request = 'linkedIn_login';
var data = $(this).serialize();
linkedInWorkAround(url,request,data);
return false;
});
}
}
else if(request == 'linkedIn_login'){
self.oauth.reset();
var pin = $(r).find('.access-code').text();
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {scope: linkedInScope, oauth_verifier: pin}, signatures: linkedInObj}).signed_url;
request = 'accessToken';
linkedInWorkAround(url,request);
}
else if(request == 'accessToken'){
var oauthRes = r.split('&');
self.oauth.reset();
$.each(oauthRes, function(k,v){
var resObj = v.split('=')
linkedInObj[resObj[0]] = resObj[1];
});
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/v1/people/~/email-address", signatures: linkedInObj}).signed_url;
request = 'getResultLinkedIn';
linkedInWorkAround(url,request);
}
else if(request == 'getResultLinkedIn'){
$('body').css({opacity:0});
var userLIemail = ($('#session_key-oauthAuthorizeForm').size()) ? $('#session_key-oauthAuthorizeForm').val() : $(r).text();
}
},
error : function(a,b,c){
alert('err')
console.log(a,b,c)
self._cs(a)
$.mobile.loading( 'hide' );
if(a.statusText.toLowerCase() == 'unauthorized'){
$('.errMsgHolder').show().text('The email address or password you provided does not match our records');
}
}
})
}
linkedInWorkAround(url,request);

Categories

Resources