Angular passing special characters in resource params decode failing - javascript

I have searching for decoding my URL substring param having forward slash which sent as %2F instead /
var Report = $resource('api/v1/report/:action/:key', {key:'#key'}, {
getById: {
method: 'GET',
params: {
action: 'abc/source'
}
},
});
I am getting exceptions while i was running some unit tests but however it is working with browser testing.
Error: Unexpected request: GET api/v1/report/abc%2Fsource/raj
How can make this always consider as /?
I also tried using javaScripts decodeURIComponent but it does not seem to work. Any Ideas
Thanks

$resource is correctly converting / to %2F, As it part of URL. Seems you need to change the URL of $resource, It can be overridden.
In resource declaration method declarion override the URL.
url – {string} – action specific url override. The url templating is supported just like for the resource-level urls.
Code
var Report = $resource('api/v1/report/:action/:key', {
key: '#key'
}, {
getById: {
url: 'api/v1/report/:action1/:action2/:key', //Override URL for getById
method: 'GET',
params: {
action1: 'abc',
action2: 'source'
}
},
});

Related

How to call php webservice url in SAPUI5?

I have tried various methods for this but I didn't get this one, can anyone give a proper solution for this? Actually, I know how to call a web service by using ajax calls, but whenever I try to pass my url as below, it gives me the following error:
onInit: function() {
$.ajax({
url:"http://SERVER_IP/SAP_DEMO/register.php",
type: "POST",
datatype:"json",
accepts:{ text:"application/json" },
success: function(oResData){
if(!oResData) {
sap.m.MessageToast.show("No Success");
}
else { sap.m.MessageToast.show(" Success"); }
},
error: function() { sap.m.MessageToast.show("unsuccessful json call"); }
});
var oModel=new sap.ui.model.json.JSONModel();
sap.ui.getCore().setModel(oModel);
}
The above code gives me this error:
error: Fiori Architectural guidelines: ESLint(sap-no-hardcoded-url): Hardcoded (non relative) url found.
In the docu here it says:
“sap-no-hardcoded-url:
Use of hardcoded URLs is not allowed.
SAP Fiori guidelines do not allow usage of hardcoded URLs to internal or external systems.
Rule Details:
Instead of references to internal systems in your URLs, you should only reference the path to the resource.”
You need to define the destination in a separate step as seen in this blog.

passing parameters to rails back end from an ajax call

I am trying to pass an API route to rails for the server to perform the call instead of the client. I get a 404 not found when I try to do this. From the console it works find when I am passing this route to the method. However not from the ajax call. Here is my controller method:
def identification
#link = params[:link]
#response = MotorClient.new.response_from_path(#link)
render json: #response
end
Here is my route:
get '/identification/:link', to: 'vehicles#identification', on: :collection
Here is my ajax:
handleRoute: function (e) {
this.handleChange(e);
e.preventDefault();
var options = e.target.options;
var route = "";
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
route = (options[i].dataset.route);
console.log(route)
$.ajax({
type: 'get',
url: '/vehicles/identification/',
dataType: 'json',
data: {"link":encodeURIComponent(route)},
success: function (data) {
this.props.getMakes(data);
}.bind(this),
})
}
}
},
When I console.log the route I get the correct string like this "/v1/Information/YMME/Years/2012/Makes/56/Models" and Like I said from the rails console it works but I can't get the parameter correctly this is what I get on the javascript console when I do thru the ajax call:
GET http://localhost:3000/vehicles/identification/?link=%252Fv1%252FInformation%252FYMME%252FYears%252F2012%252FMakes 404 (Not Found)
What am I doing wrong?
Looks like your route is expecting the link to be a segment in the URL path instead of a query string variable: /identification/:link -- Try dropping the /:link or appending the encoded link at the end of your URL when making an AJAX call back to the server.
The key here is encodeURIComponent which escapes the link string. It is better to escape data in such way, so I'm thinking you better to handle escaped string format at API side.
There is another way: using 'post' instead of 'get' ajax type. Thus, you could drop escaping part and pass a pure string as 'link' property.

JSONP - "Uncaught SyntaxError: Unexpected token"

before I explain my issue I would like to mention that I'm a naive on jsonp. This is actually my very first attempt to work with JSONP.
Im using jquery ajax call to pullback data from a website.
my jquery code is below
$.fn.checkTPS = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function() {
var api_key = 'asdfasfsadfsadfsad';
var format = 'json';
var username = 'dame#example.co.uk';
var self = $(this);
var selfValue;
var feedback = $('.tps-feedback');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()) {
selfValue = self.val();
if (selfValue.length > 9){
$.ajax({
url: 'https://www.selectabase.co.uk/api/v1/tps/' + selfValue + '/',
type: 'get',
dataType: 'jsonp',
data: {
format: format,
username: username,
api_key: api_key
},
success: function(data) {
console.log(data);
},
error: function() {
},
jsonp: 'jsonp'
});
}
}
},3000);
}
});
});
};
I want to accommodate a service from selectabase.co.uk, according to them this is how I should use the service https://www.selectabase.co.uk/api/v1/tps/[number]/?format=json&username=[username]&api_key=[api key]
when I send request using ajax I get this error Uncaught SyntaxError: Unexpected token : and when clicked this opens up
{"ctps": false, "number": "1452500705", "resource_uri": "/api/v1/tps/01452500705/", "tps": false} by the way this I want but don't know what's this error is unexpected token :
I've copied the following link from inspect element tab (you can see the image below) I think this is the call that has been generated by json https://www.selectabase.co.uk/api/v1/tps/01452500705/?jsonp=jQuery17102731868715648129_14120077325500&format=json&username=dame40example.co.uk&api_key=asdfasfsadfsadfsad&_=14120077325500
I copied the link below from inspect element > source tab in chrome.. I think I should add an image to describe properly where this json data and link I've copied from.
I hope I've manage to convey my message across... please help if you have any Idea what do i need to add... Regards
The format=json in your query string should probably be format=jsonp. The server is replying with JSON, but you're expecting a JSONP response. But I don't know that they support format=jsonp, it's just a guess.
Alternately, if that server supports CORS and allows requests from your origin, you could handle JSON instead (just remove dataType: "json" from your ajax call). Beware that that would require that the user be using a browser that properly supports CORS, which IE8 and IE9 don't. (They support CORS, but not via the normal XMLHttpRequest object, and this is a browser inconsistency that jQuery doesn't smooth over for you. If you search, though, you can find "plugins" or similar that will handle it.)

how to get correct JSON object from flickr API

I used flickr photo search method to retrieve public photos.
when I run it with jquery, it works fine, I get the json object in correct form.
{
"photos": {
"photo": [
{
.........
}
]
},
"stat": "ok"
}
But when I use it with AngularJs, I got the same object with a prefix jsonFlickrApi
jsonFlickrApi({
"photos": {
"photo": [
{
......
}
]
},
"stat": "ok"
})
what I used in AngularJs is:
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.flickrPhotoSearch = function() {
return $http({
method: 'GET',
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=3f807259749363aaa29c2fa93945&tags=india&format=json&callback=?',
dataType: 'json'
});
}
});
Please tell me how can I convert the second JSON to the first one.
Is there anything I can do in $http call or have to alter JSON object.
There was problem in the url.
This Url works for me.
https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=3f807259749363aaa29c712fa93945&user_id=61495424#N00&format=json&nojsoncallback=?
You have to add nojsoncallback=1 to the url, like this
https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=XXX&format=json&nojsoncallback=1
And that remove the jsonFlickrApi function on response.
The above answer which says to add nojsoncallback=1 is correct, but I'd like to provide more context and reasoning behind it.
If you take a look at the documentation (which is poorly formatted in my opinion): https://www.flickr.com/services/api/response.json.html and scroll all the way to the bottom you will find, tucked away:
Callback Function
If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request.
To define your own callback function name, add the parameter jsoncallback with your desired name as the value.
nojsoncallback=1 -> {...}
jsoncallback=wooYay -> wooYay({...});
The key part being: If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request
Therefore, add this to your request and it will remove jsonFlickrAPI wrapper that you are seeing in your response: nojsoncallback=1
You are getting a JSONP response (notice the P) which is basically a function call with an argument that is the response you are expecting.
Easy solution for you: Create a function named jsonFlickrApi with a parameter response and you can do your handing in there.
At this point, I am not sure if you can define your function inside your service but try it. If not, you can define it outside.
Alternatively, try using $http.get function instead. Were you specifying the return accepted by the client in your jQuery original code?
EDIT
Try this setting the data type of the request using $http or $http.get without forgetting to specify the data property in the settings object.
$http({
url: 'http://localhost:8080/example/teste',
dataType: 'json',
method: 'POST',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
$scope.response = response;
}).error(function(error){
$scope.error = error;
});

how to use custom actions in angular $resource

according to the docs i can define custom actions for each resource. This is the REST API resource I was interested in configuring (see postman import link):
http://0.0.0.0:9000/api/properties_by_address
method: POST
post data: raw json:
{
"address" : "%address%"
}
setting up the resource in my services (i called it search, see js equivalent):
window.API_HOST ="http://localhost:9000/api/";
angular.module("app.services", [])
.factory("Properties", [
"$resource"
($resource) ->
$resource API_HOST + "properties/:id", null,
search:
method: 'POST'
url: API_HOST + 'properties_by_address'
params:
hello: 'good world'
address: 'good address'
])
I try to call this in a directive like so (see this for js conversion):
.directive('homeSearch', ['Properties', (properties) ->
restrict: 'AEC'
replace: false
templateUrl: '/partials/home_search.html'
link: (scope, elem, attrs) ->
button = elem.find('.button')
button.bind "click", ->
console.log "address searched" + scope.address
properties.search {}, address: scope.address
return
])
weird stuff happens here.. first of all instead of making the mothod call 'POST' it uses 'OPTIONS' instead.. further.. it only uses the parameters set up in the default definition (ie good world, good address.. instead of the scope.address value.. which i tested to be valid) see the summary of the request/response in this chrome devtools screenshot:
questions:
- how do i make the service use the parameters that I use when i call it?
- how do i specify that it takes the parameters as post JSON data.. rather than appending it to the query string?
First, for resource, you can't default the post body as it would go against the Angular paradigm for a Resource object. Here's a better answer than I could give. Basically, the params attribute will always and only default your query string parameters.
Also, you should define your resource like this:
// Tell $resource that the 'id' property resides within the resource by using '#id'
$resource(API_HOST+ '/properties/:id', {id: '#id'}, {
search: {
url: API_HOST + 'properties_by_address',
method: 'POST'
}
});
To change the request body of your post, you're going to have to call the search function like this:
Properties.search({address: $scope.address, hello: 'good world'}, function(result){
// Do something with the response here
}, function(error) {/* handle error here if you want*/});
As far as the OPTIONS method being used, I have not seen that before. Might it be because of the API that you're requesting from? Although that may be a stretch. You may want to confer with the people that manage your server.

Categories