当我尝试连接到另一个域中的 REST 服务时出错。我知道它可以通过在 java rest 服务中添加 CORS 来解决。但是可以通过改变 Angular 方面的某些东西来实现吗?
Access to 'http://someurl/RestWeb/getPerson' XMLHttpRequest at from origin 'http://localhost:4200' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *'
我的休息服务:http://someurl/RestWeb/getPerson,我所有的休息服务网址都是这样的:http://someurl/RestWeb/SOMETHING
还有我的 Angular 网址:http://someotherurl
在搜索不同的文章后,我已经尝试更改 proxy.conf.json
和 package.json
。下面是我的更改,但我还是一样。
proxy.conf.json
{
"/RestWeb": {
"target": "http://someurl/",
"secure": false,
"changeOrigin": true // I tried with and without this. No luck
}
}
package.json
"start": "ng serve --proxy-config proxy.conf.json",
服务:
findAll(): Observable<Person[]> {
return this.httpClient.get<string[]>('http://someurl/RestWeb/getPerson');
}
运行使用:
npm start
作为临时对策,现在我正在使用
在 chrome 浏览器中测试我的应用程序chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
解决方案
{
"/RestWeb/*": {
"target": "http://someurl",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
答案 0 :(得分:2)
看来 webpack-dev-server 的代理被滥用了。
proxy.conf.json
{
"/api": {
"target": "http://someurl.com/",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
// replace `/api` with empty string, because real api path isn't contain
// `/api` segment
// eg: http://localhost:4200/api/getPerson => http://someurl.com/getPerson
"/api": ""
}
}
}
person.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class PersonService {
constructor(private http: HttpClient) {}
async getPerson() {
return (
this.http
// you shouldn't use `http://someurl.com/getPerson` url directly,
.get('/api/getPerson')
.toPromise()
);
}
}
答案 1 :(得分:1)
在您的代理配置文件中,您正在为您的 http://localhost:4200/api*
设置代理。因此,代理将不适用于 /getPerson