Angular-cli:设置代理来处理前往另一个域的复杂请求的问题

标签 angular angular-cli

我正忙于一个 Web 应用程序,它需要向本地网络上的服务器发出 http 请求。我正在使用 Angular-cli 来构建/运行我的项目。当发出任何复杂的请求时,我遇到了 CORS 问题,并尝试使用 Angular-CLI 代理来处理这些复杂的请求...我的设置与 Angular-CLI GitHub 页面上的设置完全一样,但似乎并不上类。知道我做错了什么吗?

我的代码:

proxy.conf.json:

{
"/api":{
"target":"http://10.60.160.34/BRMServices/WebEnquiry/",
"secure":false
}
}

来自 package.json:

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

具有复杂请求的函数应该发送到代理:

postStockTake(stockTakeModel: StockTakeModel) : Observable<Response> {    
  return this.http.post("/api" + "/StockTake/AddToStockTake", JSON.stringify(stockTakeModel), {headers: this.headers})
        .map((res: Response) => res.json())
        .catch((error: any) => Observable.throw(error.json().error || 'server error'));
  }

然后,我使用 npm start 而不是 ngserve 运行应用程序...当它开始构建时,我在命令提示符控制台中看到以下内容:

> barcode-checker@0.0.0 start C:\Users\User1\Documents\trade-link\barcode-checker
> ng serve --proxy-config proxy.conf.json

在我的 chrome 开发工具控制台中我看到:

zone.js:1725
POST
http://localhost:4200/api/StockTake/AddToStockTake
405 (Method Not Allowed)

所以即使我在 proxy.conf 文件的目标值中添加了本地服务器的 IP 地址,它显然仍在尝试发布到 localhost?

最佳答案

我之前也遇到过类似的问题,我发现代理 map 路径不符合预期。

当我有配置时:

{
  "/api":{
  "target":"http://10.60.160.34/BRMServices/WebEnquiry/",
  "secure":false
}

我希望所有请求都发送至 api/<sub-path>路径将映射到 http://10.60.160.34/BRMServices/WebEnquiry/<sub-path> ,但这是不正确的。

您的虚拟路径api/<sub-path>将被映射到:

http://10.60.160.34/BRMServices/WebEnquiry/api/<sub-path>

所以我得到了不正确的网址,我的服务器抛出了类似的错误。解决方案是删除不正确的 api使用下一个配置选项从我的目标 URL 获取子路径

{
  "/api": {
    "target": "http://10.60.160.34/BRMServices/WebEnquiry/",
    "secure": false,
    "pathRewrite": {"^/api" : ""}
  }
}

我有类似的问题,但没有收到答案,所以自己找到了解决我的问题的方法。

Redirect Angular2 http requests through proxy

希望这有帮助。

关于Angular-cli:设置代理来处理前往另一个域的复杂请求的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41672391/

相关文章:

angular - 构建错误 : unexpected value null exported by the module

javascript - 如何映射 Ng-repeat 中传入的值

angular - 如何在 typescript/angular 中设置子 html 元素的样式

angular - 如何获取最后发出的 Observable

javascript - 尝试使用服务在组件之间传递数据

angular - 你如何调试 Angular 6 库

css - 如何在 .angular-cli.json 中添加 css 媒体查询 angular 5

javascript - angular-cli ng 命令给出 "Unexpected token ="

angular - 响应式表单名称唯一验证器

angular - 如何配置 Karma 以包含 angular-cli 项目的全局 scss 文件?