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 控制器)中的代码的情况下从 Angular2 修复此问题?
My code
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);
您的后端似乎不接受跨域请求。
为了让它在 Angular 上工作,你必须使用代理,以便你的前端和后端使用相同的域(相同的主机名和相同的端口)
在开发模式下,您可以使用proxy.config.json
文件。假设您的后端托管在your-domain.com:80
,您的后端请求以/backend
,该文件将包含类似的内容
{
"/backend/*":{
"target": "your-domain.com",
"secure": false,
"logLevel": "debug"
}
}
通过更改 package.json 中的以下配置,使您的开发 HTTP 服务器使用此文件
"scripts": {
"start": "ng serve --proxy-config proxy.config.json",
}
不要忘记使用类似的请求来调用您的后端http://localhost:4200/backend/...
代替http://your-domain.com/...
为了让它在远程服务器上工作,您必须在 Java Web 应用程序(例如 nginx 或 Apache)上设置一个 HTTP 服务器,配置为执行与前面解释的相同的操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)