Angular App中的proxy.conf.json的CORS问题

时间:2017-11-28 16:30:54

标签: angular proxy

我在Stack Overflow上看过其他类似的问题,但到目前为止还没有为我做过任何事情。

我有一个角色应用服务http://localhost:4200。 我在http://localhost:8080/myApp/

有一个后端

我正试图通过以下电话设置从我的前端到达后端:

public getPeople(): Observable<PeopleModel[]> {
    return this.http
        .post(API_URL + '/getPeopleDetails', {})
        .map(response => {
            const people = response.json();
            console.log(people);
            return partners.map((people) => new PeopleModel(people));
        })
        .catch(this.handleError);
}

API_URL设置为http://localhost:8080/myApp

我的代理配置如下所示:

{
    "/myApp/*": {
        "target": "http://localhost:8080/myApp",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug",
        "pathRewrite" : {"^/myApp" : "http://localhost:8080/myApp"}
    }
}

我的package.json有以下内容:

"start": "ng serve --proxy-conf proxy.conf.json",

我在尝试运行应用程序时收到的错误是CORS和403.

Failed to load http://localhost:8080/myApp/getPeopleDetails: 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. The response had HTTP status code 403.

我很感激任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

在与package.json文件并行的应用程序的根目录下,创建一个新文件
proxy.config.json

{
"name":"xyz",
"version":"1.0.0",
"license":"MIT",
"angular-cli": {},
"scripts": {
    "start":"ng serve --proxy-config proxy.config.json",
    "test":"ng test"
}

现在在脚本中的 package.json :{}中,将以下带有文件名 proxy.config.json 的flax添加到 start“

{{1}}

}

希望这适合你。