localhost上的Angular2 CORS问题 [英] Angular2 CORS issue on localhost

查看:101
本文介绍了localhost上的Angular2 CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Failed to load URL: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

是否可以在不更改服务器端代码(Java Spring Controller)的情况下从Angular2修复此问题?

Is it possible to fix this from Angular2 without changing the code in server side (Java Spring Controller)?

我的代码

const headers = new Headers({'Content-Type': 'application/json',
    'Access-Control-Allow-Origin' : '*'
});
return this.http.get(url, {headers: headers})
  .toPromise()
  .then(response => response.json().data as Hero[])
  .catch(this.handleError);


推荐答案

您的后端似乎不接受跨域请求。

Your backend seems not to accept cross domain requests.

为了让它在Angular上工作,你必须使用一个代理,这样你的前端和你的后端使用相同的域(相同的主机名和相同的端口)

In order to get it to work on Angular, you have to use a proxy so that your frontend and your backend use the same domain (same host name and same port)

在开发模式下,您可以使用 proxy.config.json 文件设置代理。假设您的后端托管在 your-domain.com:80 上,并且您的后端请求以 / backend 开头,此文件包含类似

In development mode, you can set up a proxy using a proxy.config.json file. Supposing that your backend is hosted on your-domain.com:80, and your backend requests start with /backend, this file would contain something like

{
    "/backend/*":{
        "target": "your-domain.com",
        "secure": false,
        "logLevel": "debug"
    }
}

通过更改package.json中的以下配置,使您的开发HTTP服务器使用此文件

Make your development HTTP server use this file by changing the following configuration in your package.json

 "scripts": {
    "start": "ng serve --proxy-config proxy.config.json",
  }

不要忘记使用 http:// localhost:4200 / backend /等请求来调用你的后端... 而不是 http://your-domain.com / ...

为了使其在远程服务器上运行,您必须在Java Web应用程序(例如nginx或Apache)上设置一个HTTP服务器,该服务器配置为执行与之前相同的操作。

In order to get it to work on a remote server, you must set up an HTTP server over your Java web application (for example nginx or Apache) configured to do the same as explained before.

这篇关于localhost上的Angular2 CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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