Having trouble configuring CORS in Sails.js for fetching Google Maps geolocation data?

Struggling to enable CORS in my local app, I've been following the sails.js documentation which suggests changing the setting "allRoutes: true" for enabling cors. However, when attempting to access the Google API using Angular:

getLocation: function(val) {
    return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {
        params: { address: val, sensor: false }
    });
}

An error popped up in my Chrome console:
OPTIONS http://maps.googleapis.com/maps/api/geocode/json?address=an&sensor=false (index):1 XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/json?address=ui&sensor=false. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1337' is therefore not allowed access. The response had HTTP status code 405.

If anyone has a solution for this, it would be greatly appreciated. Thank you!

Answer №1

To solve the Cross-Origin Resource Sharing issue, try downloading and installing this Chrome browser plugin from the Chrome store:

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Edit:

Your endpoint setup process may include the following steps:

Firstly, run the command:

npm install request

Next:

In config/routes.js, define your route as follows:

'get /location/:keyword': {
     controller: 'location',
     action: "getlocation"
},

Create a new controller file named LocationController.js in api/controllers

In LocationController.js, implement the getlocation action.

var request = require('request');
module.exports = {
    getLocation: function(req, res) {
        var keyword = req.param('keyword');
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=' + keyword;
        request(url, function (error, response, body) {
            if (!error && response.statusCode === 200) {
                 res.jsonp({result : body});
            }
        });
    }
};

By setting up these configurations, you can now access your own endpoint without encountering CORS issues, and retrieve JSON data from the Google API.

GET : localhost:1337/location/california

Hopefully, these instructions will be beneficial to you for resolving the problem.

Regards, Richard

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

Locate an item within a JavaScript array

Similar Question: Javascript - Checking for value in array Can you spot the issue here? var zipCodes =(['90001','90002','90003']); Determine if a specific value is present in the array zipCodes if('90001' in ...

Implementing alphabetical pagination in PHP

I am trying to implement alphabetical pagination in php, but I am facing a problem. When I click on any alphabet, the selected alphabet shows up in the address bar, however, the data starting from the selected alphabet is not displayed. Here are my databa ...

displaying selected value on change in JSP

<html> <head> <title>Displaying HTML Request Parameters</title> </head> <body> <h3>Select an option:</h3> <form method="get"> <input type="text" name="usrname"><br> <select ...

What is the process for implementing a fallback image in Material UI?

Hey there! I'm currently looking to customize the fallback image of a Material UI Avatar with my own original image. Does anyone have any tips on how I can achieve this? const fallbackImage = "../../fallback/img.png" const AvatarWithBadge = ...

Gulp JS task is generating a NodeError due to the callback being triggered more than once

Error Encountered in Gulp JS Task - NodeError: Callback called multiple times Among the five Gulp JS tasks that I have, one specific task named js_bundle is causing a NodeError. The exact error message is: NodeError: Callback function called multiple ti ...

Closing and submitting a $uibmodal in Angular

Hey there, I'm a beginner in angularjs and currently experimenting with the $uibmodal feature. While I was able to successfully use $uibmodal.open, I am facing an issue that's puzzling me. Right now, my $uibmodal.close is not working as expected ...

Navigating through error messages in NextJs 14 can be tricky, especially when faced with the dreaded "ReferenceError: document not defined" or "prerendering error". It's vital to pinpoint exactly which page

When attempting to run the build on my Next.js application, I encountered an error message that is not very informative given the number of files/pages in my project. How can I pinpoint the exact location of this error and determine the root cause? The pro ...

assign a fontawesome icon to a temporary placeholder

I have tried multiple solutions from various sources, but nothing seems to be working. My goal is to apply the fontawesome icon f14a to a specific field. What am I doing wrong? document.getElementById('property_charges').setAttribute('class ...

Activate a button only when a value is inputted into a text box associated with a chosen radio button

I'm facing a challenge with my radio buttons and sub-options. When a user selects an option, the corresponding sub-options should be displayed. Additionally, I want to enable the next button only when text is entered in all sub-option text boxes for t ...

How can AngularFire update data without needing to retrieve the existing values?

Is it possible to update data by adding a number to existing data in the database, or is it necessary to retrieve the initial data first and then add the number to it? For example: this.db.object('something').update({ current:+1 // for ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

Tips for finding the *index* of distinct values in an array

My goal is to identify the indexes of unique values in an array. While I've come across various methods for removing duplicate values from an array, such as those found here: How to get unique values in an array I'm currently struggling to find ...

Problem with the "st-sort" feature in Smart-Table

Currently, I am working with angular version 1.3.15. To retrieve data, I am making an API call and then passing it to the smart table through the scope like this When checking the console, here is the data format of 'scope.rowCollection' The da ...

Enhancing user input with multiple values in a textarea using JSTL

I'm having trouble inputting multiple values into a textarea using JSTL. Here is the coding snippet I am using: <label>Resources</label> : <c:forEach items="${MEETING_ENTITY}" var="resource"> <textarea id ...

Bootstrap dropdown menu experiencing functionality issues

I am facing an issue with implementing the javascript bootstrap file in my project. The dropdown menu is not working as expected even though I have saved bootstrap to my project folder. I have tried looking at other example codes and even copied and paste ...

I have chosen Next.js for my frontend development, while our backend developer is crafting the API in Express and MySQL. I am looking for ways to secure and protect the

As a beginner frontend developer learning Next.js, I've been tasked with integrating authentication into our app. The backend developer is working on creating the API using Express and MySQL. After successful login, an accessToken is received. However ...

Out of the blue div, could you lend your assistance?

I have a code that displays 5 random images with corresponding text. My challenge is that I want to separate the text into another div so that I can add another function to it, while still keeping the images random with their corresponding text. <scr ...

Center-align the content in Material UI Typography by using the variant attribute for the caption

I'm struggling to center the content of my Typography elements with default and caption variants using the align="center" property. The alignment doesn't seem to be working properly, especially for the variant as caption. Here is a snip ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

The script ceases to function once the page is loaded from a JSON file

I'm facing an issue on my shopping website where the items and products are loaded from a JSON file. The problem is that once the page has loaded, the script fails to work properly. If the items take a little longer to load on the page, the script doe ...