Please suggest me
var rest = JSONobject[i]["descrizione"];
var descr = rest.substr(0,15);
ERROR: Cannot call method 'substr' of null
but "var rest" is NOT empty.
That's code completed:
$.ajax({
type: "GET",
url: "get_info_campotrincerato.php",
success: function (result) {
var JSONobject = JSON.parse(result);
var jnCount = JSONobject.length;
for (var i = 0; i < jnCount; i++) {
var marker = new L.Marker(new L.LatLng(JSONobject[i]["lat"], JSONobject[i]["lng"]),{ icon: myIcon1 });
var rest = JSONobject[i]["descrizione"];
var descr = rest.substr(0,15);
var list = "<dl>"
+ "<dt><b>ID:</b> " + JSONobject[i]["id"] + "</dt>"
+ "<dt>" + descr + "</dt>"
+ "<a href='?id=" + JSONobject[i]["id"] + "'>...go</a>";
marker.bindPopup(list);
marker.on('dblclick', function(e){
marker.openPopup();
});
Related
I have a middleware that it should send the request to a function, wait for it to finish and send back to the client what that function returns. the problem is I dont figure it out how to return the value that I'm getting inside a cb, hence the response is always an empty array.
const insertMultiDoc = async function (req, res) {
const documents = await uploadMultipleFiles(userData, documentsList, index);
res.send(documents);
}
here is the middleware func simplified, so documents is always an empty array. I dont return correctly from the below function
const uploadMultipleFiles = function (userData, documentsList, index) {
let savedDoc;
let savedDocuments = [];
if (pathHelper.ensureDirectoryExistence(randomFilePath)) {
mv(documentsList[index].path, randomFilePath, async function (error) {
if ((userData.email !== undefined) && (userData.component !== undefined) && (userData.email != "") && (userData.component != "")) {
var tempFileFolderPath = pathHelper.createSpecificPath(userData.component, userData, uploadTime);
var randomFilePath = path.posix.normalize(tempFileFolderPath + "/" + generatedFileName);
var inputPath = randomFilePath + '.' + fileExt;
var outputFileFFmpeg720 = tempFileFolderPath + '/720p' + generatedFileName + '.' + fileExt;
var encodedFilePath = pathHelper.createDBPath(userData.component, userData) + "/720p" + generatedFileName + "." + fileExt;
var accessFilePath = pathHelper.createDBPath(userData.component, userData) + "/720p" + generatedFileName + "." + fileExt;
const output = await fileCompresser.compressFile(inputPath, outputFileFFmpeg720);
fileSize = await getSize(output);
newDoc = createNewDocumentObject(userData.senderId, userData.senderUsername, userData.email, userData.component, userData.sessionId, fileName, fileType, accessFilePath, encodedFilePath, null, fileSize, userData.parentComponent);
savedDoc = await documentController.createLocalDocument(newDoc);
fs.unlinkSync(inputPath);
index = index + 1;
console.log(savedDoc);
savedDocuments.push(savedDoc);
}
})
}
return savedDocuments;
}
for this situation I use q module
const q= require('q');
const uploadMultipleFiles = async function (userData, documentsList, index) {
let defer = q.defer(); // create a defer
try {
let savedDoc;
let savedDocuments = [];
if (pathHelper.ensureDirectoryExistence(randomFilePath)) {
mv(documentsList[index].path, randomFilePath, async function (error) {
if ((userData.email !== undefined) && (userData.component !== undefined) && (userData.email != "") && (userData.component != "")) {
var tempFileFolderPath = pathHelper.createSpecificPath(userData.component, userData, uploadTime);
var randomFilePath = path.posix.normalize(tempFileFolderPath + "/" + generatedFileName);
var inputPath = randomFilePath + '.' + fileExt;
var outputFileFFmpeg720 = tempFileFolderPath + '/720p' + generatedFileName + '.' + fileExt;
var encodedFilePath = pathHelper.createDBPath(userData.component, userData) + "/720p" + generatedFileName + "." + fileExt;
var accessFilePath = pathHelper.createDBPath(userData.component, userData) + "/720p" + generatedFileName + "." + fileExt;
const output = await fileCompresser.compressFile(inputPath, outputFileFFmpeg720);
fileSize = await getSize(output);
newDoc = createNewDocumentObject(userData.senderId, userData.senderUsername, userData.email, userData.component, userData.sessionId, fileName, fileType, accessFilePath, encodedFilePath, null, fileSize, userData.parentComponent);
savedDoc = await documentController.createLocalDocument(newDoc);
fs.unlinkSync(inputPath);
index = index + 1;
console.log(savedDoc);
savedDocuments.push(savedDoc);
}
})
}
defer.resolve(savedDocuments); // return result
} catch (error) {
defer.reject(error) // return error
}
return defer.promise; //return a promise
}
you can check the q documentation
I have an API call to google directions API and then i
am trying to save that JSON response in a variable called as lat through this code
app.post("/from", function(req,res) {
from = req.body.from;
to = req.body.to;
const url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ from + "&destination=" + to + "&key=AIzaSyDYRICW4Bm4donS0-9LCp_h0nlsyWvEuGY";
console.log(from,to);
https.get(url, function(response) {
console.log(response.statusCode);
var buffers = []
response
.on('data', function(data) {
buffers.push(data)
})
.on('end', function() {
lat = JSON.parse(Buffer.concat(buffers).toString());
console.log(lat);
Now, inside my ejs file i want to pass this response inside a script tag in order to render a map.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12
});
var routes = directionsServiceResponse.routes;
console.log("legs " + routes[0].legs.length);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < routes[0].legs.length; i++) {
var leg = routes[0].legs[i];
for (var j = 0; j < leg.steps.length; j++) {
var step = leg.steps[j];
var color = "black";
if (step.travel_mode == "WALKING")
color = "red";
else if (step.travel_mode == "TRANSIT")
color = "green";
var polyline = new google.maps.Polyline({
path: google.maps.geometry.encoding.decodePath(step.polyline.points),
map: map,
strokeColor: color
});
google.maps.event.addListener(polyline, 'click', function(evt) {
infowindow.setContent("leg " + i + " polyline " + j)
})
for (var ii = 0; ii < polyline.getPath().getLength(); ii++) {
bounds.extend(polyline.getPath().getAt(ii));
}
}
}
map.fitBounds(bounds);
}
var directionsServiceResponse = <%= var %>
</script>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=key&callback=initMap&libraries=geometry" async defer></script>
i have tried passing that variable as a ejs variable but its not working
for (var year = year_from; year <= year_to; year++) {
for (var month = month_from; month <= 12; month++) {
for (var day = day_from; day <= 31; day++) {
var url = "something_url" + year + "/" + month + "/" + day + "/";
var current_date = day + "." + month + "." + year;
try {
var options = {
uri: url,
transform: function (body) {
var $ = cheerio.load(body);
$('div[class="post"]').each(function (month, elem) {
var nested = $(this).find('div[class="text"]');
var nested_a = nested.find('a');
var nested_href = nested_a.attr('href');
var nested_text = nested_a.text();
var lc_nested_text = nested_text.toLowerCase();
var s_lc_nested_text = lc_nested_text.toString();
if (s_lc_nested_text.indexOf(query1) > -1) {
post.name1 = s_lc_nested_text;
post.url1 = f_url + nested_href;
post.date1 = current_date;
}
});
}
};
prs.push(rp(options));
}
catch {
console.log('parse error');
}
}
}
}
Promise.all(prs)
.then((result) => {
res.send(result);
}).catch(err => console.log(err));
I get the result from the request to the API with request-promise and put it in an array of promises. After I send this result to the browser and there I get the following:
I tried the below code. The POSTMAN and console response is:
"undefined[object Object],[object Object],[object Object],[object
Object],[object Object],[object Object],[object Object],[object
Object],"
I want the correct JSON output:
exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
status: Boolean,
message: String,
data: String
};
var request = require('request');
var username =
const.username;
var password =
const.password;
var options = {
url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
auth: {
username: username,
password: password
}
};
request(options, function(error, obj) {
if (error) {
response.message = appmsg.DATA_NT_FOUND;
response.status = false;
response.data = obj;
res.send(response);
} else {
response.message = appmsg.DATA_FOUND;
response.status = true;
response.data = JSON.parse(obj.body);
//res.send(response);
var issueKey = response.data.issues;
// var keyData = issueKey[0].key;
// console.log(response.data.issues);
// console.log(keyData);
var output = [];
for (var i = 0; i < issueKey.length; i++) {
var issue = issueKey[i].key;
//var key = [];
//key.push(issue);
console.log(issue);
var respon = {
status: Boolean,
message: String,
data: String
};
var request = require('request'),
username =
const.username,
password =
const.username,
url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
request({
url: url,
headers: {
"Authorization": auth
}
}, function(err, object) {
if (object) {
var info = object;
output.push(info); // this is not working as ouput is undefined at this point
//var pout = JSON.parse(output);
//console.log(info);
console.log("==============================================================================");
//console.log(output);
console.log("******************************************************************************");
if (issueKey.length === output.length) {
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = output;
//console.log(output);
//res.send(respon);
var id = issueKey[0].id;
console.log(id);
var commitout = [];
for (var i = 0; i < issueKey.length; i++) {
var commits = issueKey[i].id;
console.log(commits);
var request = require('request'),
username =
const.username,
password =
const.password,
url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
var test = [];
request({
url: url,
headers: {
"Authorization": auth
}
}, function(err, obj1) {
if (obj1) {
var info1 = obj1;
commitout.push(info1);
var resultdone = [];
if (issueKey.length === commitout.length) {
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = commitout;
// console.log(commitout);
//var test = merge(output, commitout);
//var text = output.body[0];
resultdone.push = output + commitout;
console.log(resultdone);
res.send(resultdone);
}
}
});
}
}
}
});
}
}
});
};
What are you trying to do here: resultdone.push = output + commitout;
This concatenates your arrays, hence the [object object]s. Also Why are you assigning it to resultdone.push? I think you actually want to call the method.
Try this instead:
resultdone.push(commitout.concat(output ))
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.