CORS错误Angular 2 + Express节点 [英] CORS error Angular 2 + Express Node

查看:91
本文介绍了CORS错误Angular 2 + Express节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正面(角度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')
      } )


      }

节点(Express 4.14)

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();
});

但是我收到了CORS错误

But I got CORS Error

无法加载 https://maps.googleapis.com/maps/api/place/autocomplete/json?input=loc&types= Establishmentation& key = AIzaSyAKdEt_dYbdPY-CFo0zie23E44XxTQc1n8 : 请求中不存在"Access-Control-Allow-Origin"标头 资源.因此,不允许使用来源" http://localhost:3000 " 访问.

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.

而且在npm控制台上也没有收到任何请求.

And also did not get any request at npm console.

推荐答案

有一种API可以更简洁地完成此操作 通过脚本标签导入google map api

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>

现在从自动填充API声明服务

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);

请遵循完整示例 https://developers.google. com/maps/documentation/javascript/examples/places-queryprediction

编辑

如果您想通过快递应用程序执行此操作,则需要输入npm

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

从app.js设置错误后,为什么会出现cors错误

因为在前端您正在使用maps.google.com URL调用http服务get方法,所以在这里浏览器绝不会与您的服务器联系,它将直接进入google服务器以尝试检索内容,因此在这种情况下,除非您在angular中定义代理,否则您在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.

这篇关于CORS错误Angular 2 + Express节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆