Angular App 中 proxy.conf.json 的 CORS 问题 [英] CORS issue with proxy.conf.json in Angular App

查看:13
本文介绍了Angular App 中 proxy.conf.json 的 CORS 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've seen other similar issues here on Stack Overflow but so far nothings quite done anything for me yet.

我有一个 Angular 应用程序用于 http://localhost:4200.我在 http://localhost:8080/myApp/

I have an angular app serving to http://localhost:4200. I have a backend at http://localhost:8080/myApp/

我正在尝试通过以下调用设置从我的前端到达后端:

I'm trying to set reach the backend from my frontend with the following call:

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

the API_URL is set to http://localhost:8080/myApp

我的代理配置如下所示:

My proxy config looks like the following:

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

我的 package.json 有以下内容:

My package.json has the following:

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

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

The error I'm receiving when trying to run the app is a CORS one and a 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.

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

I'd appreciate any help. Thanks!

推荐答案

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

At the root of your application parallel to package.json file, create a new file
proxy.config.json

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

现在在您的 package.json 脚本中:{},将以下文件名为 proxy.config.json 的 flax 添加到 start">

Now in your package.json in scripts: {}, add the following flax with file name proxy.config.json to start"

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

}

希望这对你有用.

这篇关于Angular App 中 proxy.conf.json 的 CORS 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆