now, help me, I try to post data with ajax to nodejs server.
and server accept the postdata. and now i use http.get to request www.baidu.com, and want to get the html , at last return the html to front.but is error
front ajax
$("#subbtn").click(function(){
var keywords = $("#kw").val();
var target = $("#result");
if (!keywords){
target.html("<font color='#FF0000'>please key words</font>");
}
var keyArr = keywords.replace(/\,+/g, ",").split("\,");
for (var i = 0; i < keyArr.length; i++){
$.ajax({
type: "POST",
url: "http://127.0.0.1:10088",
data : { kw : keyArr[i]},
dataType: "json",
cache: false,
timeout: 5000,
success: function(data) {
alert(data.rank);return false;
// $("#result").append(data.num);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
}
});
and the server.js
// Nodejs部分,主要作用是接收前端关键词,抓取百度知道页面。返回页面给前端
var http = require('http');
var cheerio = require('cheerio');
var iconv = require('iconv-lite');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin' : '*' });
var postData = "";
var ret = 0;
req.setEncoding('utf-8');
req.addListener('data', function(chunk){
postData += chunk;
});
req.addListener('end', function(){
var value = postData.replace(/kw=/, ''), result = 0;
doRequest(value, 0);
});
res.end('{"rank":'+result+'}');
}).listen(10088);
/**
* GET请求Baidu
* #param kw 关键词
* #param page
*/
var doRequest = function(kw, page){
page = page * 10;
var options = {
host: 'zhidao.baidu.com',
port: 80,
path: '/search?word='+kw+'&pn='+page
};
http.get(options, function(res) {
var buffers = [], size = 0;
res.on('data', function(buffer) {
buffers.push(buffer);
size += buffer.length;
});
res.on('end', function() {
var buffer = new Buffer(size), pos = 0;
for(var i = 0, l = buffers.length; i < l; i++) {
buffers[i].copy(buffer, pos);
pos += buffers[i].length;
}
var gbk_buffer = iconv.decode(buffer,'GBK');
$ = cheerio.load(gbk_buffer.toString());
// 获取页面前三个的优质回答
var target = "DARRY RING";
var isBreak = false;
var htmlTop = $("#cluster-items").find(".con-all").slice(0, 3);
htmlTop.each(function(){
var tContent = $(this).text().replace(/\s+/g, "");
tContent = tContent.toLowerCase();
if (tContent.indexOf("darryring") > 0 ){ // 当找到DY的时候,退出循环
isBreak = true;
return false;
}
});
if (isBreak == true){
return {keyword : kw, score : 1};
}
var html = $("#wgt-list").find("dd.answer");
var n = 0;
html.each(function(i, elem){
var content = $(this).text().replace(/\s+/g, "");
content = content.toLowerCase();
if (content.indexOf("darryring") > 0 && n <= html.length ){ // 当找到DY的时候,退出循环
n = i + 1;
return false;
}
});
if(n == 0){
page++;
if (page < 5){
doRequest(kw, page);
}else{
return {keyword : kw, score : 9999};
}
}else{
var num = page + n;
return {keyword : kw, score : num};
}
});
res.on('error', function(e){
console.log("Got error: " + e.message);
})
})
}
Parsing POST data can be tricky business. I recommend using a module to help you out. Formaline has all the bells and whistles you'll need or poor-form is a lighter weight version.
Related
I have to write a json response in a column of tsv file how can I do that?
I am using the following code. Please find me a solution? I have to check it but its not working.
//npm init -y gen package.json file
var unProcessedItems = [];
var data = loadData('./Alabama_Pre_Final.tsv');
async function X(i) {
if (data[i] && data[i][7]) {
console.log(data[i][7]);
function address(address_details) {
request({
url: 'https://us-extract.api.smartystreets.com/?auth-id=xxx&auth-token=xxx',
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: address_details,
},
(error, response, body) => {
if (!error && response.statusCode == 200) {
var res = JSON.parse(body);
let objectArray = [];
if (res.addresses[0].verified) {
objectArray.push(res.addresses[0].api_output[0].delivery_line_1, res.addresses[0].api_output[0].last_line, res.addresses[0].api_output[0].delivery_point_barcode)
}
var address_data = objectArray.join([separator = ','])
console.log(address_data)
}
});
}
address("1000 Greenhill Blvd NW, Fort Payne, 35967, AL, USA");
const data = 'Column 19\n1\t2\t3\n4\t5\t6';
require('fs').writeFileSync('./Alabama_Pre_Final.tsv', data);
// i++;
// X(i);
}
}
}
I've looked at your answer above I think it should be easy enough to modify so that it works as you expect, I've done this below. The other functions should be left unchanged. So the function X processes each row then returns a record variable which we append to the records array. After processing is complete we write the records array to the csv file.
async function loadData(filePath) {
if (fs.existsSync(filePath)) {
var tsvData = fs.readFileSync(filePath, 'utf-8');
var rowCount = 0;
var scenarios = [];
parse_tsv(tsvData, (row) => {
rowCount++;
if (rowCount > 1) {
scenarios.push(row);
}
});
return scenarios;
} else {
console.log("loadData: Returning empty..")
return [];
}
}
// Process a row of TSV data
function X(row) {
return new Promise((resolve, reject) => {
if (row && row[7]) {
console.log(row[7]);
request({
url: 'https://us-extract.api.smartystreets.com/?auth-id=e62698e8-c3fc-b929-0f5b-d3b54d0bcd0c&auth-token=cibfMexBdl3HrmwbWY6p',
method: 'POST',
headers: { 'content-type': 'application/json' },
body: row[7],
},
(error, response, body) => {
if (!error && response.statusCode == 200) {
var res = JSON.parse(body);
let objectArray = [];
if (res.addresses[0].verified) {
objectArray.push(res.addresses[0].api_output[0].delivery_line_1, res.addresses[0].api_output[0].components.city_name,
res.addresses[0].api_output[0].components.zipcode, res.addresses[0].api_output[0].components.state_abbreviation)
}
var address_data = objectArray.join([separator = ','])
resolve({ name: address_data.replace(/['"]+/g, '') });
} else if (error) {
reject(error);
} else {
reject( { statusCode: response.statusCode });
}
});
}
});
}
async function processData() {
let MAX_RECORDS = 5; // Change as appropriate
var data = await loadData('./Alabama_Pre_Final.tsv');
if (data.length > 0) {
unProcessedItems = [];
let records = [];
for(let row of data) {
// Process a row of data.
let record = await X(row);
records.push(record);
if (records.length === MAX_RECORDS) break;
}
console.log(records);
csvWriter.writeRecords(records)
.then(() => console.log('The CSV file was written successfully'));
} else {
console.log("No Data");
}
}
processData();
const fs = require('fs');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
var rp = require('request-promise');
var dataToWrite;
var http = require("http");
var request = require('request');
function loadData(filePath) {
if (fs.existsSync(filePath)) {
var tsvData = fs.readFileSync(filePath, 'utf-8');
var rowCount = 0;
var scenarios = [];
parse_tsv(tsvData, (row) => {
rowCount++;
if (rowCount > 1) {
scenarios.push(row);
}
});
return scenarios;
} else {
return [];
}
}
function parse_tsv(s, f) {
var ix_end = 0;
for (var ix = 0; ix < s.length; ix = ix_end + 1) {
ix_end = s.indexOf('\n', ix);
if (ix_end == -1) {
ix_end = s.length;
}
//var row = s.substring(ix, ix_end - 1).split('\t');
var row = s.substring(ix, ix_end).split('\t');
f(row);
}
}
var unProcessedItems = [];
var data = loadData('./Alabama_Pre_Final.tsv');
var records = [];
async function X(i) {
if (data[i] && data[i][7]) {
console.log(data[i][7]);
var options = {
method: 'POST',
url: 'https://us-extract.api.smartystreets.com/?auth-id=c64de073-9531-9444-35e6-7204d9d62c36&auth-token=e5FxYc1niUD7Cp0peixd',
headers: {
'content-type': 'application/json'
},
body: data[i][7],
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
// POST succeeded...
var res = parsedBody;
let objectArray = [];
if (res.addresses.length) {
if (res.addresses[0].verified) {
objectArray.push(res.addresses[0].api_output[0].delivery_line_1, res.addresses[0].api_output[0].components.city_name,
res.addresses[0].api_output[0].components.zipcode, res.addresses[0].api_output[0].components.state_abbreviation)
}
var address_data = objectArray.join([separator = ','])
console.log(address_data)
// records.push({ name: address_data.replace(/['"]+/g, '') });
const ADDRESS_COLUMN_INDEX = 7;
for(let row of address_data) {
row[ADDRESS_COLUMN_INDEX] = await X(row[ADDRESS_COLUMN_INDEX]);
}
records.push(address_data.replace(/['"]+/g, ''));
let output = records.map(row => row.join("\t")).join("\n");
i++;
if (i <= 7) {
X(i);
}
else {
fs.writeFileSync('out.tsv', output);
console.log('The TSV file was written successfully');
// return callback(records);
}
}
});
}
// console.log(records);
}
if (data.length > 0) {
unProcessedItems = [];
X(0);
} else {
console.log("No Data");
}
I've updated this answer based on your last revisions, I hope this helps you:
function loadData(filePath) {
if (fs.existsSync(filePath)) {
var tsvData = fs.readFileSync(filePath, 'utf-8');
var rowCount = 0;
var scenarios = [];
parse_tsv(tsvData, (row) => {
rowCount++;
if (rowCount > 1) {
scenarios.push(row);
}
});
return scenarios;
} else {
return [];
}
}
function parse_tsv(s, f) {
var ix_end = 0;
for (var ix = 0; ix < s.length; ix = ix_end + 1) {
ix_end = s.indexOf('\n', ix);
if (ix_end == -1) {
ix_end = s.length;
}
var row = s.substring(ix, ix_end).split('\t');
f(row);
}
}
var unProcessedItems = [];
var data = loadData('./Alabama_Pre_Final.tsv');
var records = [];
async function X(i) {
if (data[i] && data[i][7]) {
console.log(data[i][7]);
var options = {
method: 'POST',
url: 'https://us-extract.api.smartystreets.com/?auth-id=c64de073-9531-9444-35e6-7204d9d62c36&auth-token=e5FxYc1niUD7Cp0peixd',
headers: {
'content-type': 'application/json'
},
body: data[i][7],
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(async function (parsedBody) {
// POST succeeded...
var res = parsedBody;
let objectArray = [];
if (res.addresses.length) {
if (res.addresses[0].verified) {
objectArray.push(res.addresses[0].api_output[0].delivery_line_1, res.addresses[0].api_output[0].components.city_name,
res.addresses[0].api_output[0].components.zipcode, res.addresses[0].api_output[0].components.state_abbreviation)
}
var address_data = objectArray.join([separator = ','])
console.log("rp.then -> address_data:",address_data);
data[i][7] = address_data.replace(/['"]+/g, '');
records.push(data[i].join("\t"));
i++;
if (i <= 7) {
console.log("Looking up address #" + i);
X(i);
} else {
const output = records.join("\n");
// Remove the _test when you are happy with the result.
fs.writeFileSync('./Alabama_Pre_Final_test.tsv', output);
console.log('The TSV file was written successfully');
}
}
});
}
}
if (data.length > 0) {
unProcessedItems = [];
X(0);
} else {
console.log("No Data");
}
I using that API to create resumable Upload in Drive.
It worked but i can't receive response data from Promise
Here is my code:
var fs = require('fs');
var request = require('request');
var mime = require('mime');
var _ = require("underscore");
class resumableUpload {
constructor(credentials,token,options={}){
this.credentials = credentials; // object from json credentials
this.token = token; // object from token credentials
this.new_token = {};
this.expiry_token_time = 0;
this.options = Object.assign({
size:256*1024,
retry:-1
},options)
}
refresh_token(){
return new Promise((ok,faild)=>{
var now = new Date().getTime();
if(now>this.expiry_token_time){
request.post("https://www.googleapis.com/oauth2/v4/token",{
form:{
refresh_token:this.token.refresh_token,
client_id:this.credentials.client_id,
client_secret:this.credentials.client_secret,
redirect_uri:this.credentials.redirect_uris[0],
grant_type:'refresh_token'
}
},(err,httpResponse,body)=>{
if(err) faild(err);
this.new_token = JSON.parse(body);
this.expiry_token_time = now + this.new_token.expires_in*1000;
ok(this.new_token.access_token);
})
}else{
ok(this.new_token.access_token);
}
})
}
/*
Upload Resumable
file:{
name:'name of file',
path:'path/to/file'
}
*/
upload(file){
return new Promise((ok,faild)=>{
this.refresh_token().then((access_token)=>{
console.log(access_token);
this.file_len = fs.statSync(file.path).size;
var form = {};
if(!_.isEmpty(file.name)) form.name = file.name;
if(!_.isEmpty(file.parents)) form.parents = [file.parents];
request.post({
uri:'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
headers:{
'Authorization':`Bearer ${access_token}`,
'Content-Type':'application/json; charset=UTF-8',
'X-Upload-Content-Type':mime.getType(file.path),
'X-Upload-Content-Length': this.file_len,
'Content-Length':new Buffer(JSON.stringify(form)).length
},
body:JSON.stringify(form)
},(err,res,body)=>{
if(err || _.isEmpty(res.headers.location)){
if ((this.retry > 0) || (this.retry <= -1)) {
this.retry--;
return this.upload(file); // retry
} else {
//console.log(body);
faild("Over retry");
}
}else{
var location = res.headers.location;
//console.log("URL UPLOAD: ",location);
this.sendUpload(location,file).then((data)=>{
console.log("UPLOAD DONE!!!");
ok(data);
}).catch((err)=>{
console.log("ERROR: ",err);
faild(err);
});
}
})
}).catch(faild)
})
}
sendUpload(api,file,start=0){
return new Promise((ok,faild)=>{
this.refresh_token().then((access_token)=>{
var end = parseInt(start+this.options.size-1);
if(start>=this.file_len) ok("DONE");
if(end>=this.file_len) end = this.file_len - 1;
var headers = {
'Authorization':`Bearer ${access_token}`,
'Content-Length': parseInt(end - start + 1),
'Content-Range':`bytes ${start}-${end}/${this.file_len}`
}
var uploadPipe = fs.createReadStream(file.path, {
start: start,
end: end
})
uploadPipe.pipe(request.put({uri:api,headers:headers}).on('response',(res)=>{
if(res.statusCode == 308){
//console.log(res.headers);
var new_start = parseInt(res.headers.range.split('-')[1]);
console.log("Percent: "+(new_start/this.file_len*100).toFixed(2)+" %");
return this.sendUpload(api,file,new_start+1);
}else if(res.statusCode == 200 || res.statusCode == 201){
console.log("percent: 100 %");
//ok({status:"OK"});
}
}).on('error',(err)=>{
if ((this.retry > 0) || (this.retry <= -1)) {
this.retry--;
console.log("Retry Again");
return this.sendUpload(api,file,start);
}else{
faild("Over retry");
}
}).on('data',(data)=>{
if(!_.isEmpty(data)){
console.log(data.toString());
ok(data.toString());
}
}))
}).catch(faild)
})
}
}
module.exports = resumableUpload;
In that code - sendUpload function, I split my file to many chunk and upload it in to drive.
when I upload the last chunk, server will response statusCode is 200 or 201.
It console.log "percent: 100 %" and received data from that response.
My data of response like it:
{
"kind": "drive#file",
"id": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"name": "test-video",
"mimeType": "video/mp4"
}
But, the Resolve (ok function) not call, cause in upload function, i can't receive it in then function. it mean i can't see "UPLOAD DONE!!!" in screen.
Resloved: Thanks for Roamer-1888
In Pipe, return a promise not work. I change return this.sendUpload(...) to this.sendUpload(...).then(ok,faild) and it worked.
Success localhost response
Cannot GET /u/coupons at server
Frontend script for post
<script>
var count = document.getElementById("count");
var len = document.getElementById("length");
var pattern = document.getElementById("pattern");
document.getElementById('coupons-button').onclick = function()
{
if(count.value!=="" && len.value!=="")
{
const genReq = new XMLHttpRequest();
let url = `count=${encodeURI(count.value)}&` +
`len=${encodeURI(len.value)}&` +
`pattern=${encodeURI(pattern.value)}`;
genReq.open('POST',`/u/coupons?${url}`,true);
genReq.send();
genReq.onreadystatechange = e => {
if(genReq.readyState === 4 && genReq.status === 200){
let gen = JSON.parse(genReq.response);
if (gen.state === "SUCCESS")
{
var coupons = gen.coupons;
for(var i=0;i<coupons.length;i++)
{
var div = document.createElement('div');
var text = document.createTextNode(coupons[i]);
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
} else {
var div = document.createElement('div');
var text = document.createTextNode("FAIL TO GENERATE");
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
}
}
}
}
Server script
admin.post( '/u/coupons' ,(req,res)=>{
let params = getParameters(req);
CouponWorker.generateCoupons({
"len":decodeURI(params.len),
"count":decodeURI(params.count),
"pattern":decodeURI(params.pattern)
}).then((_res) =>{
console.log(_res)
if(_res.success === true)
{
res.status(200).json({
"state":"SUCCESS",
"coupons":_res.coupons
});
}
else{
res.status(200).json({"state" : "FAILED"});
}
});
});
CouponWorker
const firebase = require('./Database');
const voucher_codes = require('voucher-code-generator');
exports.generateCoupons = function(params)
{
var len = params.len;
var count = params.count;
var pattern = params.pattern;
//pattern = pattern.replace(/1/g,'#');
const cpn_db = firebase.firebase.database();
var coupons;
return new Promise((resolve,reject)=>{
coupons = voucher_codes.generate({
length:len,
count:count,
prefix:"AMP-",
pattern: '####-####',
charset:"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ"
});
if(coupons!==null)
{
for(var i =0;i<count;i++)
{
cpn_db.ref('coupons/cid-'+coupons[i]).set({
"addedOn": getDateTime(),
"code" : coupons[i],
"amount" : 20,
"expireDate" : null,
"isActive" : true,
"isDeleted":false
});
}
resolve({
"success":true,
"coupons":coupons
});
}
else
{
resolve({
"success":false
});
}
});
}
Above given snaps shows the same code running on localhost and server,
localhost working fine,giving output and saving data to firbase while server response 404 not found resource.
I can not find the reason of this error.I tried url req on postman and responses are the same as above
I have been unable to to successfully parse the returned token to authenticate final Paypal sandbox payment process. Any help or input would be greatly appreciated :)
REF:
https://github.com/petersirka/node-paypal-express-checkout
https://developer.paypal.com/docs/classic/express-checkout/in-context/integration/
Here is the error I am returned:
ACK: 'Failure',
VERSION: '52.0',
BUILD: '22708556'
L_ERRORCODE0: '10410',
L_SHORTMESSAGE0: 'Invalid token',
L_LONGMESSAGE0: 'Invalid token.',
L_SEVERITYCODE0: 'Error'
Client side:
<form id="myContainer" method="post" action="/api/payment/payone"></form>
<script>
window.paypalCheckoutReady = function () {
paypal.checkout.setup('XXX', {
environment: 'sandbox',
container: 'myContainer'
});
};
</script>
<script src="//www.paypalobjects.com/api/checkout.js" async></script>
API:
payone: function(req, res) {
var paypal = require('paypal-express-checkout').init('username', 'password', 'signature', 'return url', 'cancel url', 'debug');
paypal.pay('20130001', 10.00, 'XX', 'USD', false, function(err, url) {
if (err) {
console.log(err);
return;
}
res.redirect(url);
});
paypal.detail( "token", "PayerID", function(err, data, invoiceNumber, price) {
if (err) {
console.log(err);
return;
}
});
}
Finally, paypal-express doc:
var parser = require('url');
var https = require('https');
var qs = require('querystring');
function Paypal(username, password, signature, returnUrl, cancelUrl, debug) {
this.username = "XXX";
this.password = "XXX";
this.solutiontype = 'Mark';
this.signature = "XXX";
this.debug = debug || false;
this.returnUrl = 'XXX';
this.cancelUrl = 'XXX';
this.url = 'https://' + 'api-3t.sandbox.paypal.com' + '/nvp'; //'https://' + (debug ? 'api-3t.sandbox.paypal.com' : 'api-3t.paypal.com') + '/nvp';
this.redirect = 'https://' + 'www.sandbox.paypal.com/cgi-bin/webscr'; //https://' + (debug ? 'www.sandbox.paypal.com/cgi-bin/webscr' : 'www.paypal.com/cgi-bin/webscr');
};
Paypal.prototype.params = function() {
var self = this;
return {
USER: self.username,
PWD: self.password,
SIGNATURE: self.signature,
SOLUTIONTYPE: self.solutiontype,
VERSION: '52.0'
};
console.log(self);
};
Paypal.prototype.detail = function(token, payer, callback) {
if (token.get !== undefined && typeof(payer) === 'function') {
callback = payer;
payer = token.get.PayerID;
token = token.get.token;
}
console.log(token);
var self = this;
var params = self.params();
params.TOKEN = token;
params.METHOD = 'GetExpressCheckoutDetails';
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, data);
return;
}
if (typeof(data.CUSTOM) === 'undefined') {
callback(data, null);
return;
}
console.log('3.3');
var custom = data.CUSTOM.split('|');
var params = self.params();
params.PAYMENTACTION = 'Sale';
params.PAYERID = payer;
params.TOKEN = token;
params.AMT = custom[1];
params.CURRENCYCODE = custom[2];
params.METHOD = 'DoExpressCheckoutPayment';
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, data);
return;
}
console.log('3.4');
callback(null, data, custom[0], custom[1]);
});
});
return self;
};
Paypal.prototype.request = function(url, method, data, callback) {
var self = this;
var params = qs.stringify(data);
if (method === 'GET')
url += '?' + params;
var uri = parser.parse(url);
var headers = {};
headers['Content-Type'] = method === 'POST' ? 'application/x-www-form-urlencoded' : 'text/plain';
headers['Content-Length'] = params.length;
var location = '';
var options = { protocol: uri.protocol, auth: uri.auth, method: method || 'GET', hostname: uri.hostname, port: uri.port, path: uri.path, agent: false, headers: headers };
var response = function (res) {
var buffer = '';
res.on('data', function(chunk) {
buffer += chunk.toString('utf8');
})
req.setTimeout(exports.timeout, function() {
callback(new Error('timeout'), null);
});
res.on('end', function() {
var error = null;
var data = '';
if (res.statusCode > 200) {
error = new Error(res.statusCode);
data = buffer;
} else
data = qs.parse(buffer);
callback(error, data);
});
};
var req = https.request(options, response);
req.on('error', function(err) {
callback(err, null);
});
if (method === 'POST')
req.end(params);
else
req.end();
return self;
};
Paypal.prototype.pay = function(invoiceNumber, amount, description, currency, requireAddress, callback) {
// Backward compatibility
if (typeof(requireAddress) === 'function') {
callback = requireAddress;
requireAddress = false;
}
var self = this;
var params = self.params();
params.PAYMENTACTION = 'Sale';
params.AMT = prepareNumber(amount);
params.RETURNURL = self.returnUrl;
params.CANCELURL = self.cancelUrl;
params.DESC = description;
params.NOSHIPPING = requireAddress ? 0 : 1;
params.ALLOWNOTE = 1;
params.CURRENCYCODE = currency;
params.METHOD = 'SetExpressCheckout';
params.INVNUM = invoiceNumber;
params.CUSTOM = invoiceNumber + '|' + params.AMT + '|' + currency;
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, null);
return;
}
if (data.ACK === 'Success') {
callback(null, self.redirect + '?cmd=_express- checkout&useraction=commit&token=' + data.TOKEN);
return;
}
callback(new Error('ACK ' + data.ACK + ': ' + data.L_LONGMESSAGE0), null);
});
return self;
console.log(self);
};
function prepareNumber(num, doubleZero) {
var str = num.toString().replace(',', '.');
var index = str.indexOf('.');
if (index > -1) {
var len = str.substring(index + 1).length;
if (len === 1)
str += '0';
if (len > 2)
str = str.substring(0, index + 3);
} else {
if (doubleZero || true)
str += '.00';
}
return str;
};
exports.timeout = 10000;
exports.Paypal = Paypal;
exports.init = function(username, password, signature, returnUrl, cancelUrl, debug) {
return new Paypal(username, password, signature, returnUrl, cancelUrl, debug);
};
exports.create = function(username, password, signature, returnUrl, cancelUrl, debug) {
return exports.init(username, password, signature, returnUrl, cancelUrl, debug);
};
Usually we encounter Error 10410 if there is incorrect token or no token passed.
please make sure that you are passing the right PayPal Express token.
for information on error codes you may refer: https://developer.paypal.com/docs/classic/api/errorcodes/
I have a problem with my nodejs git branches test. This is the code:
var exec = require('child_process').exec;
var request = require('request');
var cheerio = require('cheerio');
var async = require('async');
var currentDir = ""; // dir
var getBranches = "git for-each-ref --sort=-committerdate refs/remotes/origin/ --format='%(refname:short)'";
var getAuthors = "git for-each-ref --sort=-committerdate refs/remotes/origin/ --format='%(committername)'";
var branches = [];
var errorBranches = [];
var authors = [];
var manager = [];
var result = [];
var fs = require('fs');
var openedBranches = "";
var outFile = 'BranchesTest-results.xml';
var failuresFound = false;
function eliminateDuplicates(arr) {
'use strict';
var i,
out = [],
obj = {};
for (i = 0; i < arr.length; i++)
obj[arr[i]] = 0;
for (i in obj) {
if (obj.hasOwnProperty(i))
out.push(i);
}
return out;
}
function showBranchesStats(branches, cb) {
'use strict';
console.log("in showBranchesStats method\n");
var branchesName = [];
var committers = [];
var temp = [];
var j = 0,
k = 0;
for (var i = 0; i < branches.length; i++) {
var filter = branches[i].match(/(md|dr)[_\-](\d+)/i);
if (filter !== null) {
filter = filter[1] + '-' + filter[2];
temp[j] = authors[i];
branchesName[j++] = filter;
}
else {
if (!branches[i].match(/(develop|master|HEAD)/ig))
errorBranches[k++] = branches[i];
}
}
var obj = {};
for (i = 0; i < branchesName.length; i++)
obj[branchesName[i]] = 0;
for (i in obj) {
if (obj.hasOwnProperty(i))
committers.push(temp[branchesName.indexOf(i)]);
}
branchesName = eliminateDuplicates(branchesName);
errorBranches = eliminateDuplicates(errorBranches);
var closedBranches = [];
var tasks = [];
j = 0;
for (i = 0; i < branchesName.length; i++) {
tasks.push(getTask(i));
}
tasks[0]();
var endedCounter = 0;
function onEnd() {
if (++endedCounter < branchesName.length) {
console.log(endedCounter + '/' + branchesName.length);
tasks[endedCounter]();
return;
}
console.log("All requests finished\n");
for (var i = 0; i < manager.length; i++) {
result[i] = [];
result[i] = closedBranches[i].slice(0, -1).split("\n");
}
TestResult(cb);
}
function getTask(i) {
return function () {
console.log("Request #" + i + "\n");
request('SERVERNAME' + branchesName[i] + '?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel#issue-tabs', function (error, response, html) {
if (!error && response.statusCode === 200) {
var $ = cheerio.load(html);
try {
var data = $('.actionContainer:contains("Closed")');
if (data.length > 0) {
//var _manager = ('not(.twixi-wrap)', data).last().children().eq(0).children().children().eq(0).text();
var _manager = committers[i];
var _hasClosed = ('not(.twixi-wrap)', data).last().find(".activity-new-val").text().indexOf("Closed");
if (_manager && _hasClosed) {
var flag = false;
for (var s = 0; s < manager.length; s++)
if (manager[s] === _manager)
flag = true;
if (_hasClosed !== -1) {
if (j >= 0 && flag === false) {
manager[j++] = _manager;
closedBranches[manager.indexOf(_manager)] = "";
}
closedBranches[manager.indexOf(_manager)] += "SERVERNAME" + $('title').text().substring(2, 9) + "\n";
}
else
openedBranches += "SERVERNAME" + $('title').text().substring(2, 9) + " --- OPENED [OK] ----\n";
}
}
else
openedBranches += "SERVERNAME" + $('title').text().substring(2, 9) + " --- OPENED [OK] ----\n";
}
catch (ex) {
console.log("Something wrong happened with your request. Details: " + ex);
}
onEnd();
}
else {
console.log("Something wrong happened with your request. Details: " + error);
failuresFound = true;
cb();
}
});
};
}
}
function TestResult(cb) {
'use strict';
console.log("Results file constructing started\n");
outFile = fs.openSync(outFile, 'w');
fs.writeSync(outFile, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
fs.writeSync(outFile, "<testsuites>\n");
for (var i = 0; i < manager.length; i++) {
fs.writeSync(outFile, "\t<testsuite name=\"" + manager[i] + "\">\n");
for (var j = 0; j < result[i].length; j++) {
fs.writeSync(outFile, "\t\t<testcase name=\"" + result[i][j] + "\">\n");
fs.writeSync(outFile, "\t\t\t<failure message=\"Branch Test Failure\">\n");
fs.writeSync(outFile, "\t\t\t\tError! Found closed branch: " + result[i][j] + "\n");
fs.writeSync(outFile, "\t\t\t</failure>\n");
fs.writeSync(outFile, "\t\t</testcase>\n");
failuresFound = true;
}
fs.writeSync(outFile, "\t</testsuite>\n");
}
console.log("\nOpened branches: \n\n" + openedBranches);
if (!failuresFound) {
fs.writeSync(outFile, "\t<testsuite name=\"BranchTest\">\n");
fs.writeSync(outFile, "\t\t<testcase name=\"BranchTest\"/>\n");
fs.writeSync(outFile, "\t</testsuite>\n");
}
fs.writeSync(outFile, "</testsuites>");
fs.closeSync(outFile);
console.log("\nError branches: \n");
for (var k = 0; k < errorBranches.length; k++)
console.log(errorBranches[k]);
console.log('Test result : ' + (failuresFound ? '' : 'no ') + 'failures found');
cb();
}
this.check = function () {
'use strict';
console.log("Execution started\n");
var funcs = [
function (cb) {
console.log('started 1');
exec(getAuthors, {cwd: currentDir}, function (error, stdout, stderr) {
console.log('started 1.1');
if (stderr) {
console.log('stderr: ' + stderr + "\n");
failuresFound = true;
cb();
}
else {
authors = stdout.split('\n');
console.log("Authors has been received\n");
cb();
}
if (error !== null) {
console.log('Execution command error: ' + error + "\n");
failuresFound = true;
cb();
}
});
},
function (cb) {
console.log('started 2');
exec(getBranches, {cwd: currentDir}, function (error, stdout, stderr) {
console.log("started 2.1");
if (stderr) {
console.log('stderr: ' + stderr + "\n");
failuresFound = true;
cb();
}
else {
branches = stdout.split('\n');
console.log("Going to showBranchesStats method\n");
showBranchesStats(branches, cb);
}
if (error !== null) {
console.log('Execution command error: ' + error + "\n");
failuresFound = true;
cb();
}
});
}
];
console.log('async.waterfall');
async.waterfall(funcs, function () {
console.log("Execution finished\n");
return !failuresFound;
});
};
it' all works just perfect locally, but when i'm trying to run it in command line or on Jenkins like this:
grunt test_Branches
something wrong happens & i get this log:
+ npm i
+ grunt test_Branches
[4mRunning "test_Branches" task[24m
Execution started
async.waterfall
Done, without errors.
Help, pls!
I resolved the problem. The solution is here.
You need rightly use asynchronous functions.