Cross domain HTML parsing using AngularJS [duplicate] - javascript

This question already has an answer here:
Why does my JSONP request give me Uncaught SyntaxError: Unexpected token < (less than)?
(1 answer)
Closed 5 years ago.
We are working on java project in which backend is java + spring and fronted is angular 2 + HTML.
I want to do cross domain html parsing but we don't have permission to access external links on server side as we have some security issues for outsite domains, so we have to get the DOM content of link on client side using jquery.
I have tried these:
var url = "http://xyz.aspx";
$http({
method: 'JSONP',
url: url,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).
success(function(response) {
$scope.test = response;
}).
error(function(status) {
//your code when fails
});
The external link which I need to parse contains many href links. I also need to parse content of those links.
Have tried above mentioned code:
getting error in console - Uncaught SyntaxError: Unexpected token < on
xyz.aspx page
What will be best solution to get content of the pages and pass to server side for parsing?

Solution 1)
getting error in console - Uncaught SyntaxError: Unexpected token < on xyz.aspx page
This means that the server callback isn't a valid JavaScript application. Please ensure your server returns a valid JavaScript application. In that way this error will go away. JSONP needs a valid JavaScript application response to make it work. For example this is how a JSONP callback should look like:
jsonCallback(
{
sites: [
{
siteName: "Test"
}
]
}
);
Solution 2)
If your server side does not return a JSON Object try to use a GET request and enable CORS.
$http({
method: 'GET',
url: "http://xyz.aspx",
}).success(function(response) {
$scope.test = response.data;
}).error(function(status) {
//your code when fails
});
Solution 3)
If you are still be unable to add CORS to your backend you could create an PROXY application yourself. This for example is an public CORS Proxy https://crossorigin.me/. Adding an example on how to create a proxy service would be to much. Please research by yourself. There are a lot of examples in the web.

See ng.$http. Your URL is missing the callback parameter,instead of giving like
json_callback: 'JSON_CALLBACK'
Try below way
$http({
method: 'jsonp',
url: 'http://xyz.aspx?callback=JSON_CALLBACK',
params: { name: 'xyz' }
}).success(function(data, status , header, config) {
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});

Related

Angular http GET 405 (Method Not Allowed)

I'm implementing another function in an application (made with angular), I call an API (made with Lumen) and it returns a 405 error whem i tried in local and "XMLHttpRequest cannot load Response for preflight is invalid (redirect)" when i tried on the server. I read about CORS but it's already implemented, I think if it isn't none of others functions would work.
Another thing, if I make the call with Advanced Rest Client it works fine :(
sorry about my english, i don't speak it so much.
function on application
$scope.agencias = [];
$http({
method: 'GET',
//url: 'http://api-beta.grupoaldorf.com.mx/agencias/',
url: 'http://localhost:8000/agencias/',
headers: agenciaMazda.headers
}).then(function successCallback(response) {
$scope.agencias = response.data;
console.log("regreso del http");
console.log($scope.agencias);
}, function errorCallback(response) {
//callback(false);
});
route on web.php
$app->get('agencias','CitasController#agenciasDisponibles');
controller in CitasController.php
public function agenciasDisponibles(Agencia $agencia){
$fabricante = $this->request->header('Aldorf-App');
$disponibles = Agencia::where('fabricante', $fabricante)->where('mostrar', 1)->select(['codigo', 'nombre'])->get();
return $disponibles;
}
Finally i solved it, it was really dumb, i added a slash at the end of the uri xD it had to be "http://localhost:8000/agencias" instead of "http://localhost:8000/agencias/"

How to "get" from NodeJS with AngularJS

I started an AngularJs App and to retrieve some data from database I'm using NodeJS (totally new to me), on the console of NodeJS it works and also typing the URL directly in the browser but when I try to get the information needed using http.get() in AngularJS using the same URL in the browser I get 404 not found.
I figured it would be a cors problem so I added
require('cors') in the nodeJS app and still doesn't work
Can anyone help me with that ?
Am I right making separate apps for Angularjs in front-end and NodeJS in the Backend or should I assemble them in only one application ?
Thank you for your help
This is the AngularJS code:
$scope.keyLoad = function () {
$http.get("localhost:8080/product")
.success(function (response) {
$scope.keys = response;
console.log(response)
})
};
$scope.keyLoad();
I get 404 not found. I figured it would be a cors problem
If it says it is a 404 error then it is a 404 error and not a CORS problem.
Look at your code:
$http.get("localhost:8080/product")
That URL is missing the scheme. It is a relative URL.
You are going to be requesting something like http://example.com/myapp/localhost:8080/product.
Put http:// or https:// in front of it.
You should use $http service.
For example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Or
$http.get('/someUrl', config).then(successCallback, errorCallback);

Angular HTTP GET request returns undefined while working in browser

I'am learning AngularJs and I've tried to write a very basic script sending an http request to Ebay public API, I've signed up and got my API keys, I've read the docs several times and wrote this basic code :
$scope.getQueryUrl = function () {
// Some unrelated code ...
$scope.queryUrl["Ebay"] = "http://svcs.sandbox.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-NAME=FindingService&SERVICE-VERSION=1.0.0&GLOBAL-ID=EBAY-US&SECURITY-APPNAME="+dataAuth.EbayKeyApi+"&RESPONSE-DATA-FORMAT=XML&keywords="+$scope.qtext ;
};
$scope.sendRequest = function () {
$scope.getQueryUrl(); // Gets the query url after adding all the parameters
alert($scope.queryUrl.Ebay);
$http.get($scope.queryUrl["Ebay"]).then(
function(response){
alert("success" + response.data );
},
function(response){
alert("error" + response.statusCode );
});
};
How this code should work :
It should create a formated Ebay query url, send it through HTTP GET request and sending back the response .
Note : $scope.qtext & dataAuth.EbayKeyApi are already assigned with their respective values .
What's the problem:
The problem is that using this Angularjs script, the code doesn't work, the alert "Error" is shown, and the response.statusCode is undefined .
But when I copy the formatted Ebay query link in Firefox it works perfectly and the XML response is shown .
The formatted Ebay query was generated using the script provided .
I think it's a header related problem .
$http has some default headers defined. $http sends Json payload and accepts Json as the response by default. Since you are dealing with XML you have to explicitly specify the accepted response type as XML using the header:
Accept: application/xml
Please use the following function with appropriate headers and you should get the response. Also, please look into any Cross Origin Resource Sharing (CORS) restrictions on the ebay API.
function getRequest(url) {
$http({
method: "GET",
url: url,
headers: {
'Content-Type': 'application/xml, text/xml',
'Accept': 'application/xml, text/plain, * / *'
}
})
.then(function (response) {
alert(response.data);
},
function (error) {
alert (error);
});
}
Thank you,
Soma.

Getting a parseerror from jQuery $.ajax post return using jsonp from Trakt.tv api

Working with the Trakt.tv API. It looks like I'm sending valid json as I'm able to authenticate but the return I receive is a parse error.
Resource interpreted as Script but transferred with MIME type text/html:
http://api.trakt.tv/recommendations/shows/myApiKeyCompleteNumbers?callback=jQuery111000155555475132972_1397674204444&{%22username%22:%22userName%22,%22password%22:%22mySha1PassComplete%22}&_=1397674207093
Uncaught SyntaxError: Unexpected identifier
The return says:
Disallowed Key Characters.
I'm using:
jQuery 1.11.0
Thanks in advance for any help or guidance
$(document).ready(function () {
function success(data) {
alert('data: ' + data);
}
var traktUser = 'myUserName';
var traktHash = 'mySha1Password';
var traktApi = 'myApiKey';
var data = {
'username': traktUser,
'password': traktHash
};
var postData = JSON.stringify(data);
var apiUrl = 'http://api.trakt.tv/recommendations/shows/' + traktApi;
$.ajax({
type: 'POST',
url: apiUrl,
data: postData,
contentType: 'application/json',
dataType: 'jsonp',
}).
done(success);
}); //document ready
You can't make a POST request using JSONP, jQuery is ignoring the POST instruction and making a GET request.
Your data is being placed in the query string and is not properly URL Encoded.
The server is responding with an HTML document containing an error message instead of a JavaScript script formatted according to JSONP rules.
It looks like the API you are trying to use does not support JSONP at all. Since you are passing your own user credentials in the request, this makes sense. JSONP is a hack to work around the Same Origin Policy that is implemented by browsers (these days we can use CORS instead) and there is no point in using it unless you want end user browsers to access the API directly. Since end user browsers couldn't access it without being given your username and password, it doesn't seem likely to be intended to be used that way.
Process the data from the API on your server instead.

How I get respone text in application and bind to the label in cross ajax call

I am calling the web service from other domain using Ajax call and I want to get returned response from server in my application by using following code I get response text in firebug but not in my JavaScript code. Control are not showing success and error response it goes out directly.
I want response in my success or error section but both not handling in this.
I am trying lot but not finding any solution please any one help me.
I am in a trouble. I hope somebody can help me for calling cross domain web service by using Ajax call. I am trying from 1 week but didn't find any solution till. I am getting response on browser but not getting it on my actual code.
My JavaScript code.
crossdomain.async_load_javascript(jquery_path, function () {
$(function () {
crossdomain.ajax({
type: "GET",
url: "http://192.168.15.188/Service/Service.svc/GetMachineInfo?serialNumber="+123,
success: function (txt) {
$('#responseget').html(txt);
alert("hii get");
}
});
crossdomain.ajax({
type: "POST",
url: "http://192.168.15.188/Server/Service.svc/GetEvents/",
// data: "origin=" + escape(origin),
success: function (txt) {
$('#responsepost').html(txt);
alert("hii post");
}
});
});
});
</script>
You can't simply ignore the Same Origin Policy.
There are only three solutions to fetch an answer from a web-service coming from another domain :
do it server-side (on your server)
let the browser think it comes from the same domain by using a proxy on your server
change the web service server, by making it JSONP or (much cleaner today) by adding CORS headers

Categories

Resources