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

标签 angular proxy

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

我有一个 Angular 应用程序服务于 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.

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

最佳答案

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

{
"/api*": {
    "target":"http://localhost:8080",
    "secure":false,
    "logLevel":"debug"
    }
}  

现在在您的 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"
}

}

希望这对你有用。

关于angular - Angular App 中 proxy.conf.json 的 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47536466/

相关文章:

MySQL 代理逐步配置

html - 当我在 Angular 中单击它时,如何在导航中获取名称菜单

unit-testing - Angular 2.0.0 - 测试 "imported by the module ' DynamicTestModule' "

docker - 如果不在localhost代理-> vpn上,则docker-compose端口转发不起作用

git拒绝在没有代理的情况下连接

nginx url 重写与代理传递示例?

java - 通过代理连接到远程 weblogic 服务器时出现问题

javascript - Gulp:如何使用 js 库的 CDN?

angular - 如何取消订阅路由解析类中的可观察对象

javascript - Angular 7 : close menu when click outside