Angular-cli:设置代理以处理进入另一个域的复杂请求的问题

use*_*257 2 angular-cli angular

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

我的代码:

proxy.conf.json:

{
"/api":{
"target":"http://10.60.160.34/BRMServices/WebEnquiry/",
"secure":false
}
}
Run Code Online (Sandbox Code Playgroud)

来自package.json:

"start": "ng serve --proxy-config proxy.conf.json",
Run Code Online (Sandbox Code Playgroud)

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

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'));
  }
Run Code Online (Sandbox Code Playgroud)

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

> barcode-checker@0.0.0 start C:\Users\User1\Documents\trade-link\barcode-checker
> ng serve --proxy-config proxy.conf.json
Run Code Online (Sandbox Code Playgroud)

在我的chrome dev工具控制台中,我看到:

zone.js:1725
POST
http://localhost:4200/api/StockTake/AddToStockTake
405 (Method Not Allowed)
Run Code Online (Sandbox Code Playgroud)

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

Vad*_*imB 6

之前我遇到过类似的问题,我发现代理映射路径不像预期的那样.

当我有配置:

{
  "/api":{
  "target":"http://10.60.160.34/BRMServices/WebEnquiry/",
  "secure":false
}
Run Code Online (Sandbox Code Playgroud)

我希望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>
Run Code Online (Sandbox Code Playgroud)

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

{
  "/api": {
    "target": "http://10.60.160.34/BRMServices/WebEnquiry/",
    "secure": false,
    "pathRewrite": {"^/api" : ""}
  }
}
Run Code Online (Sandbox Code Playgroud)

我有类似的问题,但没有得到答案所以找到解决我自己的问题.

通过代理重定向Angular2 http请求

希望这可以帮助.