I am using combination of Node and Angualr JS alongwith express-4
In my code I am trying to send newSourceId via res.send . I am able to get the newSourceId but when I send it using res.send it gets into error instead of getting in to success.
I also tried using res.sendStatus(newSourceId) but no luck!
Following is the Node JS part:
app.post('/addObservationDetail',function(req,res){
var newSourceId = -1;
Observation.create({obv_source:req.body.source,obv_waveband:req.body.waveband,prpsl_id:req.body.pId}
).then(function(result) {
Observation.findAll({
attributes: [['obv_id','id']],where:{prpsl_id:req.body.pId},order: [["obv_id","DESC"]],limit: 1
}) .then(function(rows) {
console.log("Obv_Id is = "+rows[0].dataValues.id);
newSourceId=rows[0].dataValues.id;
console.log("newsrc===="+newSourceId);
res.send(newSourceId);
});
});
});
This is the Angular JS part:
$scope.updateObsDet = function(obs_detail,index) {
var url = "/";
if(obs_detail.sourceId == null){
url += "addObservationDetail";
$http({
method:'POST',
url:url,
headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest:function(obj){
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data:{source:obs_detail.source,waveband:obs_detail.waveband,pId:$scope.proposal.proposalId}
}).success(function(data){
alert("New observation added"); //should come in here
updateSourceId(data,index,obs_detail);
}).error(function(data){
alert(data); //getting in here
});
} else {
url += "updateObservationDetail";
data = {
source:obs_detail.source,
waveband:obs_detail.waveband,
sourceId:obs_detail.sourceId
};
$http.post(url,data).success(function(data){
alert(data);
}).error(function(data){
alert(data);
});
}
};
PS: I can not change the angular Part of the code, changes need to be done in the Node JS part.
yes you can set json response try this
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});
app.listen(3000);
Related
i use Jive and i want to get all categories and for each category, i want to create a checkbox for each of them.
Currently, i have my array with all categories, but when i try to create checkbox, it return me this error :
" Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/ "
Someone can help me ?
///////////////// function checkbox for each category ////////////////
$("#submit_a_question").click(function(e) {
e.preventDefault();
$("#modal").addClass('is-show');
$("#ideasContainer").height((height + 100) + "px");
resizeIframe();
fieldsPlaceholder(appLang);
var categoriesToShow = categories(placeID);
var container = $('#listCheckboxCategories');
var listCheckboxCategories = $('#listCheckboxCategories');
var CheckboxCreate = $('input />', {type: 'checkbox'});
if(tileConfig.isThereFilterRadios == "Yes"){
$('#ShowCategories').show();
$('#listDropdownCategories').show();
$.each(categoriesToShow.res, function(index, value) {
CheckboxCreate.appendTo(container);
});
}
///////// function to get all categories in an array /////////
function categories(placeID){
var request = osapi.jive.corev3.places.get({
uri : '/api/core/v3/places/' + placeID
});
// var res = [];
request.execute(function(response) {
if (typeof response.error != 'undefined') {
console.log("API call failed");
} else {
console.log(response);
response.getCategories().execute(
function (res){
console.log("cat",res);
});
}
});
}
I was able to execute the call successfully by using "/places/{placeId}" in the URI as below:
osapi.jive.corev3.places.get({uri: '/places/1003'}).execute(function(response) {
console.log(response);
});
For which I have received the place object in the response, as expected:
{ type: "space",
parent: "http://localhost:8080/api/core/v3/places/1000",
placeTopics: Array(0),
displayName: "water-cooler",
iconCss: "jive-icon-space", …}
Are you sure your "placeId" has the correct value? Maybe log the URI you are sending before making the call and check if the format matches the one I have mentioned above. Thanks.
I have a piece of angular code that does a post request to the cloudant, returns a response, builds a URL with it and does a get request with the same. The get request returns an array buffer through which i build a PDF file to be rendered in the front end.
Could someone please let advice me on how to unit test this as unit testing along with rest API is a new territory for me . PFB my code
$scope.viewfile = function(name) {
$http({
method : 'POST',
url : '/search/searchFiles',
data : {'currentdropdownvalue' : name} ,
}).
success(function(data){
if (!angular.isUndefined(data.docs[0])){
$scope.file = data.docs[0]._id;
var fileUrl = $scope.cloudantUrl + $scope.file +"/"+ $scope.file;
$http.get(fileUrl {responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
$scope.contentType = "application/pdf";
$scope.contentWords = null;
}).error(function(data){
console.log("Printing Error inside Post of view " , data);
});
}
else{
$scope.content = null;
$scope.contentWords = "File is not available for the selected Name";
}
}).
error(function(data){
console.log("Printing Error inside view " , data);
});
};
}
Ideally you should probably use $httpBackend but I usually just end up putting a spy on these functions. Heres some sudo code using spyOn:
it('Should test viewFile', function() {
spyOn($http, 'POST').andReturn(mock_data);
spyOn($http, 'GET').andCallFake(function(fileUrl) {
expect(fileUrl).toBe($scope.cloudantUrl + $scope.file +"/"+ $scope.file);
});
$scope.viewFile(mocked_name).then(function() {
expect($scope.content).toBe($sce.trustAsResourceUrl(fileURL));
expect($scope.contentType).toBe("application/pdf");
expect($scope.contentWords.toBe(null);
});
$rootScope.$apply();
});
I'm developing a Wikipedia Viewer and I'm trying to extract some data from the Wikipedia API. This is supposed to be a normal request, any idea why this method is not giving any response? I'm using fetch library.
The line console.log(data) doesn't run at all.
function getArticleList() {
var searchFor = "";
searchFor = document.getElementById('intext').value;
console.log(searchFor);
fetch("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchFor + "&limit=5").then(function(resp) {
console.log("trySearch");
return resp.json()
}).then(function(data) {
console.log(data);
document.querySelector.artName.innerText = data.object[1];
document.querySelector.textArt.innerText = data.object[0];
document.querySelector.href = data.object[2]
})
};
From Wikimedia's documentation: 'For anonymous requests, origin query string parameter can be set to * which will allow requests from anywhere.'
The following worked for me:
fetch("https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=Belgium&limit=5").then(function(resp) {
console.log(resp);
return resp.json()
}).then(function(data) {
console.log(data);
Notice that I filled in my own search with 'Belgium', but your code should work with the right modifications.
Any particular reasons to use fetch library ? This can be done using simple Jquery AJAX.
function getArticleList() {
var searchFor = document.getElementById('intext').value;
var response="";
console.log(searchFor);
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=opensearch&search="+searchFor+"&limit=5",
dataType: 'jsonp',
success: function(data){
console.log(data);
response=data;
}
}).done(function(response) {
console.log(response);
document.querySelector.artName.innerText = response.object[1];
document.querySelector.textArt.innerText = response.object[0];
document.querySelector.href = response.object[2];
});
};
I am writing a simple app where I need to get the data from a http get api call and store it in Parse for some reason not all the data is stored. Also the http call returns before saving all the data here is the code.
How can I make it to return only after saving all the data?
Parse.Cloud.httpRequest({
url: 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=apikey',
success: function(httpResponse) {
var jsonobj = JSON.parse(httpResponse.text);
var total = jsonobj.movies.length;
for ( var idx in jsonobj.movies) {
var movie = new Movie();
movie.save(new Movie(jsonobj.movies[idx])).then(
function(object){
console.log(object)
},
function(error){
console.log(error);
}
)
}
response.send("All saved");
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.send("Failed");
}
})
You need to aggregate all the promises you used via an aggregation function, in the case of parse promises, it's .when :
Parse.Cloud.httpRequest({
url: 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=apikey',
success: function(httpResponse) {
var jsonobj = JSON.parse(httpResponse.text);
var total = jsonobj.movies.length;
var results = [];
// do NOT iterate arrays with `for... in loops`
for(var i = 0; i < jsonobj.movies.length; i++){
var movie = new Movie();
results.push(movie.save(new Movie(jsonobj.movies[i]))); // add to aggregate
}
// .when waits for all promises
Parse.Promise.when(promises).then(function(data){
response.send("All saved");
});
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.send("Failed");
}
})
Although, it might be better to use promises for the httpRequest too, this should work.
Hi now I know that NodeJS is asynchronous (which I am still trying to get my head around to be honest).
The problem that I am currently facing is I have attempting to do a http.request to receive some JSON data. This is fine but what I need is to return this data to a variable. I believe I need to do a callback function? (from what I have read up on the matter)
The Code that I currently have:
var http = require('http');
pCLatLng = '';
function postCodeCheck() {
var pCode = {
host: 'geo.jamiethompson.co.uk',
path: "/" + 'SW1A2AA' + ".json"
};
http.request(pCode).on('response', function(response) {
var data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
pCJSON = JSON.parse(data);
pCLatLng = pCJSON;
});
}).end();
}
console.log(pCLatLng);
This is obviously outputting "undefined"; I have tried returning the response.on('end') when having return "hi" or anything inside it instead NodeJS outputs the information about the site. If anyone can help with this it would be much appreciated.
console.log(pCLatLng); needs to be inside (or inside something called by) the response.on('end' callback. The value isn't available until that callback is fired.
Try something like:
function postCodeCheck(callback) {
var pCode = {
host: 'geo.jamiethompson.co.uk',
path: "/" + 'SW1A2AA' + ".json"
};
http.request(pCode).on('response', function(response) {
var data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
callback(JSON.parse(data));
});
}).end();
}
postCodeCheck(function (pCLatLng)
{
console.log(pCLatLng);
});
You want something like this:
var http = require('http');
function postCodeCheck(cb) {
var pCode = {
host: 'geo.jamiethompson.co.uk',
path: "/" + 'SW1A2AA' + ".json"
};
http.request(pCode).on('response', function(response) {
var data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
var pCJSON = JSON.parse(data);
cb(pCJSON);
});
}).end();
}
postCodeCheck(function(pCLatLng) { console.log(pCLatLng); });
Look carefully for the differences before using.
You'll need your postCodeCheck() function to take a callback as well, just like http.request. In the world of async, calling callbacks with results takes a similar role to returning results.