使用Angular 7作为前端,使用Java作为后端时遇到CORS错误
我正在本地桌面上运行两个应用程序 一个是内置java作为API,另一个是内置Angular作为前端应用程序 我试图从Angular访问后端数据,但遇到错误: CORS策略已阻止从源“”访问“”处的XMLHttpRequest:否 “Access Control Allow Origin”标头出现在请求的服务器上 资源使用Angular 7作为前端,使用Java作为后端时遇到CORS错误,java,angular,cors,frontend,backend,Java,Angular,Cors,Frontend,Backend,我正在本地桌面上运行两个应用程序 一个是内置java作为API,另一个是内置Angular作为前端应用程序 我试图从Angular访问后端数据,但遇到错误: CORS策略已阻止从源“”访问“”处的XMLHttpRequest:否 “Access Control Allow Origin”标头出现在请求的服务器上 资源 publicGetMethod():可观察{ 返回此文件。http .get(API_URL) .map(响应=>{ }) .接住(这个.把手错误); } 我在Angular中做
publicGetMethod():可观察{
返回此文件。http
.get(API_URL)
.map(响应=>{
})
.接住(这个.把手错误);
}
我在Angular中做了类似的事情来获取数据,错误不断出现
我的问题是,这是角度错误还是后端错误(Java)?这是后端错误。您必须在java后端允许cors。选中在本地发出http请求的简单方法是在浏览器中安装cors扩展 例如,如果您使用Google Chrome安装它:
因此,在按钮中单击启用cors并发出请求:)在项目根目录中
package.json
旁边创建一个proxy.conf.json
这里有一个例子
{
"/service/*": {
"target": "http://localhost:8080",
"changeOrigin": true
}
}
将您的proxy.conf.json
添加到angular.json
中的service
选项中。例如:
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "app:build",
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"browserTarget": "app:build:production"
}
}
}
就这样。只需像往常一样ng serve
,您就可以开始代理服务器了。确保不要在http
调用中手动提供主机url
。只需从/service
请求您的后端使用哪种框架?100%后端错误。使用反向代理在同一域上托管API,或者禁用CORS头。
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "app:build",
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"browserTarget": "app:build:production"
}
}
}