How can I use HTTPS in AngularJS? - javascript

I am using AngularJS, $resource & $http and working with apis, however due to security reason I need to make an HTTPS request (work under the HTTPS protocol).
What's the way to use https in AngularJS.
Thanks for your help.

For some reason Angular would send all requests over HTTP if you don't have a tailing / at the end of your requests. Even if the page itself is served through HTTPS.
For example:
$http.get('/someUrl').success(successCallback); // Request would go over HTTP even if the page is served via HTTPS
But if you add a leading / everything would work as expected:
$http.get('/someUrl/').success(successCallback); // This would be sent over HTTPS if the page is served via HTTPS
EDIT: The root cause of this problem is that Angular looks at the actual headers from the server. If you have an incorrect internal pass of http data through https there will still be http headers and Angular would use them if you do not add / at the end.
i.e. If you have an NGINX serving content through https, but passing requests to Gunicorn on the backend via http, you might have this issue. The way to fix that is to pass the correct headers to Gunicorn, so your framework would be under the impression of being served via https. In NGINX you can do this with the following line:
proxy_set_header X-Forwarded-Proto $scheme;

Use the $http api as you would normally:
$http.get('/someUrl').success(successCallback);
if your app is being served over HTTPS then any calls you are making are to the same host/port etc so also via HTTPS.
If you use the full URIs for your requests e.g. $http.get('http://foobar.com/somePath') then you will have to change your URIs to use https

I've recently run into similar issues using Angular 1.2.26, but only when interacting through a load-balancer - which may be stripping https-related headers...not sure of cause yet. I've resorted to this:
uri = $location.protocol() + "://" + $location.host() + "/someUrl"
You might want to add $location.port() also if using a non-standard port.

Related

How to solve CORS error while fetching an external API?

I'm developing a web app in Angular 10 that works as follows:
I'm dealing with CORS issue. I do not have permission to add code to the server I'm fetching.
I want to be able to:
Fetch the website
Parse the result, and put it in my database
I'm aiming to deploy the solution on an Apache server.
Here is the CORS error I'm dealing with:
Blocking a Cross-Origin Request: The "Same Origin" policy does not
allow viewing the remote resource located at
https://wwwfrance1.CENSORED.eu.com/api/?apikey=CENSORED.
Reason: "Access-Control-Allow-Origin" CORS header is missing. Status
code: 200.
Here is what i've tried:
Using MOSIF mozilla extension (works, but not sustainable for deployment, and for some reason, when I'm ignoring the CORS security, I cannot post on my DB any more)
Adding a header in my fetching request, such as:
/******API SEACH****/
/***Global Update***/
private updateClients() {
let xmlRequestPromise = fetch('https://wwwfrance1.CENSORED.eu.com/api/?apikey=CENSORED&service=list_clients', {
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*',
}
})
.then(async response => this.clients = this.regexSearchClient(await response.text()))
return xmlRequestPromise
}
But that doesn't work either. I've verified that the header appears in the request.
How to proceed?
What is CORS ?
Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. From wiki
In simple terms only an internal webserver can send Requests which are potentially dangerous to it's web server, and requests from other server's are simply blocked.
But few HTTP requests are allowed ,Few of the allowed methods are GET, HEAD, POST.
How do I resolve the issue ?
Apparently in this circumstance you cannot send a fetch request to a web server having CORS header. Instead you can do a GET request to the web server as a web server having CORS allows HTTP GET requests.
Note - If you send a GET request to a web server using angular in your browser it wouldn't work as browser's convert GET requests into fetch requests and fetch requests aren't allowed from a web server with CORS. Instead send a GET request from a webserver/local machine rather than a browser.
Create your own server and make a route which fetches that API. From your Angular application fetch that route on your server.
You have to use a package as a middleware. If you are using nodejs-framework expressjs.At first, you have to run npm install cors -force.Then add the code that is given bellow:-
const cors=require('cors')
app.use(cors({origin:true}))

Trying to retrieve JSONP from HTTP server from a HTTPS website

I have a website based on HTTPS, and I have a JS code the get data from a website based on HTTP. I get an error that the HTTP server is not trusted.
While the same code works on HTTP to HTTP. But not on HTTP to HTTPS.
This is the error:
Mixed Content: The page at 'https://www.33k.com/player/playerudan.php' was loaded over HTTPS, but requested an insecure script 'http://33k.thepuremix.net/json.xsl'. This request has been blocked; the content must be served over HTTPS.
For getting this data I use something like the following code:
var URL = "http://33k.thepuremix.net/json.xsl"
$.getJSON( URL, function( data) {
console.log( data );
});
Any idea how to fix it or make it working. Is there such a Crossdomain.xml on Icecast that I can give configure or anything else to fix it?
UPDATE:
The above links are two different websites. It is not a sub-domain matter. The links just look alike a bit. Domain A(HTTPS) wants to get JSON from domain B (HTTP).
Calling HTTP from HTTPS is blocked by design as #RoryMcCrossan mentioned in the comments (Same Origin Policy), you can either move your script from HTTP to HTTPS or make a backend script (in PHP for example) and call HTTP from it like:
JavaScript(HTTPS) -> PHP(HTTPS) -> PHP(HTTP)
JavaScript(HTTPS) <- PHP(HTTPS) <- PHP(HTTP)
Reference to creating a http request in PHP: Http Request in PHP
Here's also some info about Same Origin Policy

How to access HTTPS API from HTTP server using AJAX

I am trying to integrate an API request with jQuery but I get a "Mixed Content" error because my website is HTTP:// and the API website is HTTPS://. I dont'want to use an SSL certificate on my site. How I can communicate with the API?
This is the code I use:
jQuery(document).ready(function() {
alert("hello");
jQuery.post('http://example.net/privacy/test.php',function(data) {
alert(JSON.stringify(data));
});
});
and use:
$.getJSON('//www.mindicador.cl/api', function(data) { ... });
Is this possible? Thanks for the help.
You cannot bypass this directly.
You could work around the issue by setting up an HTTP domain that server-side just gets the content of the HTTPS site and returns it, thereby bypassing the HTTPS issues since the new domain's JavaScript would be running from an HTTP domain and so could call the HTTP endpoint.
Or you could proxy the call, by setting up (or using some existing) HTTPS endpoint, and having that endpoint call the HTTP endpoint and return the contents it gets from the HTTP endpoint. That way the JavaScript on the HTTPS domain is only ever talking to HTTPS endpoints.

How to use jQuery GET on HTTP (non-secure) server?

I'm getting this error when I try to use $.get on a non-secure site (ie. http, not https):
jquery.min.js:4 Mixed Content: The page at '...' was loaded over HTTPS, but requested an insecure script 'http://api.openweathermap.org/data/2.5/weather?lat=50&lon=2?callback=jQuery...'. This request has been blocked; the content must be served over HTTPS.
I've been trying to think of work-around solutions to this. The problem is a fixed one, since the server is hosted by OpenWeather.org and it's a non-secure site (ie. http, not https).
This is my request code:
$.get("https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=123456", function(data) {
tempC = data.weather.main.temp / 10; // OpenWeather API returns Celsius * 10
rain = data.rain["3h"];
clouds = data.clouds.all;
});
Simply changing the request URL to https://api.openweathermap.org... doesn't work, of course. Tried it and didn't work.
The only solution I can think of right now is to find another weather API that is free to use for my project, but I'd like to know if there's a way to still use OpenWeathermap's API, given that it's http. Curious to know this because it seems quite wasteful to have to dismiss certain APIs just because it's http and not https.
Found another post on SO about the same "mixed content" issue. It's helpful and points to many other resources to solve the problem.
The asker ended up dropping openweathermap API (because it's served over HTTP) and using forecast.io's API instead (served over HTTPS while still free).
Using Open Weather Map which is HTTP only through an HTTPS website and NOT get mixed content warning
so, the Problem is, that you run your code on a HTTPS site(JSFiddle and Coodepen). Your browser will not allow HTTP-Connections on a HTTPS site for security-reasons. You can solve that issue by either forcing HTTP on the page where you run your code(try to run a code from a local file or localhost) or you could create a HTTPS -> HTTP forwarding on your server, that would receive a HTTPS request from your code and send a HTTP-request to API.
I would suggest first try to run from a localhost or local file(not sure if every browser will allow AJAX from a local file, but you can try before setting up localhost), that should work for you. If you just want to test the API you can simple copy the URL of the GET-request into you browser tab and execute it.

Serving static files in connectjs with 'Access-Control-Allow-Origin' set to '*'

I'm using Connect.js to serve my static files in a Node.js application; however, I want to be able to make GET requests to those static files from multiple origins, so I'd like to be able to set 'Access-Control-Allow-Origin' : '*' in the response header for these static files.
My question is, how would I go about doing this with Connect? Here's my server so far:
var connect = require('connect');
var server = connect(
connect.static(__dirname + '/public')
);
server.listen(8080);
Access-Control-Allow-Origin only applies to ajax requests, generally speaking. When you're serving static files, you don't need to worry about that particular header. Anyone can request those files, regardless of origin, in the default configuration.
You run into issues when you serve a regular page, and then you want to request via javascript FROM that page. Then you need to set your Access-Control-Allow-Origin policy to allow ajax requests to other domains from that particular page.
Further, you most often run into this when attempting to access a web service. Its very common to use JSONP in those cases, instead of using that particular header. Especially not * since it introduces security risks. See http://www.ibm.com/developerworks/library/wa-aj-jsonp1/ and http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
MDN resource: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Josh

Categories

Resources