AngularJS and the challenge of working with Google API's across different domains

I have been using the code below to obtain location details from the Google API.

This is my code:

 if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position){
      $scope.$apply(function(){
        $http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude+'&sensor=true').then(function(res){
          alert(res.data);
        });


      });
    });
  }

However, when I run this code, I encounter a Cross domain Error.

The error message reads as follows:

XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/json?latlng=8.5663029,76.8916023&sensor=true. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

I am seeking suggestions on how to resolve this issue.

Answer №1

When making a request, be mindful of the Authorization header being sent as it triggers a CORS preflight check that Google disapproves of

To resolve this issue, simply exclude the Authorization header from your API call

Try implementing the following code snippet:

$http.get("your shortened url", {headers: {Authorization: undefined}})

Note that I swapped out the actual URL for clarity purposes

Another alternative suggestion involves using the $http "general" request format instead of the $http.get shortcut:

$http( {
     method: 'GET',
     url: 'someurl',
     headers: {
       'Authorization': undefined
     }
   }
 )

By adopting this approach, you can steer clear of the CORS preflight check while ensuring the smooth execution of your API calls

Answer №2

Encountered a similar issue when utilizing the satellizer module for authentication. https://github.com/sahat/satellizer

Per the FAQ section: "How can I prevent sending Authorization header on all HTTP requests?"

This approach worked for me:

$http({
  method: 'GET',
  url: 'your google api URL',
  skipAuthorization: true  // `Authorization: Bearer <token>` will not be included in this request.
});

Implementing this fix resolved the issue, possibly due to interference from a third-party module altering the header.

Answer №3

Unfortunately, I am unable to respond directly to the original comment, but

It seems like you might be utilizing Interceptors within your AngularJS application, which could potentially modify your request after you initially configure it:

{headers: { Authorization: null } }

I am currently conducting further research to address this issue. I will share my findings at a later time.

[Edit] Wed Jul 13 2016 21:38:03 GMT-0500 (CDT) [/Edit]

To work around this problem, I have opted to utilize pure Javascript instead. By bypassing the Interceptors in the $http Service, my request is not intercepted and does not include the Authorization header.

Hopefully, this solution may be beneficial to others facing similar challenges.

Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a loader when making an AJAX request and then conceal it after it has successfully completed

I find myself a bit puzzled here. Currently, I'm developing a JavaScript form that sends values to a PHP page (submit.php). If the PHP page returns a success message, I plan to redirect the user to another page (success.php). var url = 'submit. ...

I want to modify a script for toggling a div's visibility to utilize a select dropdown menu instead of radio buttons

CSS @charset "utf-8"; /* CSS Document */ body,td,th { font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, sans-serif; font-size: medium; } body form select { font-family: "Gill Sans", "Gill Sans MT", "Myriad ...

Implementing distinct usernames using Firebase's simplelogin

Recently, I followed a tutorial on Thinkster to create a web app using Angular and Firebase. In the tutorial, the Firebase simpleLogin method is used to create a 'profile' with a username. Factory: app.factory('Auth', function($fireb ...

What is the best way to include a title and a close button at the top of a menu, before the first item, when a button menu is clicked in material-ui?

One of the challenges I'm facing is adding a title to an icon button menu that contains a checkbox list of menu items. When the user clicks on the icon and opens the dropdown, I want the title to appear at the top of the dropdown along with a close bu ...

Explore jQuery UI Tabs with remote content, highlighting the active tab with a link to the current page

Back in earlier versions of jQuery UI (<=1.8), when loading tabs, the link for a remote tab would be replaced with a local link. This allowed users to middle-click (or open in new browser tab) on the tab, and it would link back to the current page with ...

Save data from localStorage to clipboard with a click of a button

Imagine you have a total of 25 different names stored in localStorage. How can you easily copy and paste this data from localStorage to clipboard by simply clicking buttons? Take a look at the button code that is designed to copy the localStorage data: & ...

PHP AJAX for a Multi-Select Form

Hi there, I'm having some trouble with PHP AJAX to display the result in a select field. My goal is to have the second select field appear after choosing an option in the first one, and then load the third select field when selecting an option in the ...

Fetching data in React hooks can be done without relying on useEffect or setTimeout. Instead, you can utilize other methods to achieve

INFORMATION* const Information = (props) { const { fetchNewest, retrieveAllData } = useRoom(); const [ data, setData ] = useState([]); const [ status, setStatus ] = useState([]); useEffect(() => { const fetchData = async () ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...

Iterating through JavaScript objects using the foreach method

I'm having difficulty with a JavaScript algorithm. I am working with Vue as my framework and state management tool. I have an object that needs to be 'calculated' as variants. For instance, I have 3 objects with some values as arrays, like ...

Attempting to connect information to state using an input field that is being iterated over in React

Struggling with binding state values to input values using an onChange function handleChange = event => { this.setState({ [event.target.name]: event.target.value }); }; The issue arises when the Input fields are within a map and assi ...

Can you share the method for concatenating an object at a specific index within an Array using JavaScript?

Currently, I have an array arr = [object1, object2, object3]. After removing the second index, the array now looks like arr = [object1, object3], and I am looking to add back the removed object2 at its original position in the array so that it becomes a ...

What is the best way to split the vertices of a mesh in Three.js?

Is there a way to disassemble the vertices of a Three.js mesh? I am interested in tearing apart a 3D object using mouse input. Recently, I developed a GLSL vertex shader for this web application that shifts the vertices of a mesh based on the brightness of ...

Utilize URL parameters in Node.js and Express for effective communication

I have an endpoint ..com When I perform a curl call, the endpoint looks like this: ..com?param1=true Now, I am attempting to make a similar call from Node.js. However, I'm uncertain about whether param1 should be included in the headers, concatenate ...

Attempting to modify the key values within an object, however, it is mistakenly doubling the values instead

I'm encountering an issue when trying to update key values within an object. It seems to be adding duplicate values or combining all values together instead of assigning each name a specific language slug. I can't figure out where I'm going ...

Ways to make webpack load the umd bundle of a library

Currently, I am working on a hybrid application that combines Angular1 and Angular2, utilizing webpack as the package bundler. Within my code, I import the library (@angular/upgrade) using the following syntax: import { UpgradeModule } from '@angula ...

Ways to retrieve data from various MongoDB collections in state with Express?

MongoDB Relationship Dilemma Trying to implement a many-to-many relationship in MongoDB, I am faced with the challenge of reading documents from multiple collections within the same database. Within my backend script server.js, I am fetching data from col ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Combine two redux actions and access the modified state in the second action

I'm facing a dilemma with a straightforward problem that I believe I have a solution for, but I'm uncertain about the effectiveness of my idea. Essentially, in the current state of things, I have an array property that requires updating just bef ...

Is there a different option besides using the scale() function in CSS for transforming elements

It's a well-known fact that elements with the CSS property position: fixed don't behave as expected when the container has the transform property applied in CSS. After searching through various threads, I couldn't find a definitive solution ...