CORS error Angular 2 + Express Node

一曲冷凌霜 提交于 2019-12-22 17:58:30

问题


Front side(Angular 2)

public googlesearch(ev:Event){
    this.http.get("https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ev.target.value+"&types=establishment&key=AIzaSyAKdEt_dYbdPY-CFo0zie23E44XxTQc1n7").map(res => $.parseJSON(res)).subscribe( data => {
      this.predictions = data.predictions;
      console.log(this.predictions);
     },(error) =>{ 
       alert('Not able to get')
      } )


      }

Node (Express 4.14)

var app = express();
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

But I got CORS Error

Failed to load https://maps.googleapis.com/maps/api/place/autocomplete/json?input=loc&types=establishment&key=AIzaSyAKdEt_dYbdPY-CFo0zie23E44XxTQc1n8: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

And also did not get any request at npm console.


回答1:


That header has to be set by the target url server, https://maps.googleapis.com/ in your case. setting header on your server will not help.

you can, however-

  1. find an appropriate api that allows calls from browser.
  2. implement a proxy to that url on your server and call it from browser.



回答2:


There is an api for doing it in a cleaner way import the google map api via an script tag

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initService"
    async defer></script>

And now declare an service from the autocomplete API

function initService(){
   autoService = new google.maps.places.AutocompleteService();
}

And in your event listener just do this

autoService.getQueryPredictions({ input: event.target.value }, displaySuggestions);

Follow for the full example https://developers.google.com/maps/documentation/javascript/examples/places-queryprediction

EDIT

If you want to do it from your express application there is an npm for it

https://www.npmjs.com/package/googleplaces

Why are you getting an cors error after setting it up from your app.js

Because in the front end you are calling the http service get method with your the maps.google.com url so here in no way the browser will contact your server it will go directly to the google server trying to retrieve the content so your configuration in app.js is useless in this case unless your define a proxy in your angular.



来源:https://stackoverflow.com/questions/46758154/cors-error-angular-2-express-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!