代理配置无法使用角度CLI

Arj*_*ngh 9 http-proxy angular-cli angular

8080 - 托管后端的端口4200 - 我的Angular2前端

在My Angular2项目中,我有文件proxy.config.json,内容如下

{
  "/api": {
  "target": "http://localhost:8080",
  "secure": false,
  "changeOrigin": "true",
  "pathRewrite": {"^/api": ""}
 }
}
Run Code Online (Sandbox Code Playgroud)

在Angular2 package.json中,我将启动过程更改为"start": "ng serve --proxy-config proxy.config.json" 当我在命令器中输入时,npm start然后在开始时我可以看到代理创建:/ api - > http:// localhost:8080.好吧,到目前为止我觉得很好.

我正在尝试发送请求(Angular2)

  constructor(private http: Http) {
    this.getUsers();
  }

  getUsers(): any {
    return this.http.get("/api/getusers")
      .subscribe(response => {
        console.log(response);
      })
  }
Run Code Online (Sandbox Code Playgroud)

我收到一个错误http:// localhost:4200/api/getusers 404(Not Found).我们可以看到,没有任何代理.为什么?我做错什么了吗?

visual studio代码的控制台输出是

 10% building modules 2/2 modules 0 active[HPM] Proxy created: /api/  ->  http://localhost:8080
[HPM] Proxy rewrite rule created: "^/api" ~> ""
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]
Hash: d102bcd0909a1776c844
Time: 27041ms
chunk    {0} main.bundle.js, main.bundle.map (main) 13.6 kB {2} [initial] [rendered]
chunk    {1} styles.bundle.js, styles.bundle.map (styles) 130 kB {3} [initial] [rendered]
chunk    {2} vendor.bundle.js, vendor.bundle.map (vendor) 3.87 MB [initial] [rendered]
chunk    {3} inline.bundle.js, inline.bundle.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.
[HPM] Rewriting path from "/api/getusers" to "/getusers"
[HPM] GET /api/getusers ~> http://localhost:8080
Run Code Online (Sandbox Code Playgroud)

这是浏览器控制台响应:

GET http://localhost:4200/api/getusers 404 (Not Found)
error_handler.js:54 EXCEPTION: Response with status: 404 Not Found for URL: http://localhost:4200/api/getusers
Subscriber.js:238 Uncaught Response {_body: "<html><head><title>Apache Tomcat/7.0.47 - Error re…hade"><h3>Apache Tomcat/7.0.47</h3></body></html>", status: 404, ok: false, statusText: "Not Found", headers: Headers…}
Run Code Online (Sandbox Code Playgroud)

isu*_*uAb 5

我试过这种方法。我的 proxy.conf.json 文件是这样的:

{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false,
    "changeOrigin": "true",
    "pathRewrite": {"^/api": ""}
  }
}
Run Code Online (Sandbox Code Playgroud)

我已经在 package.json 中替换"start": "ng serve"了这个"start": "ng serve --proxy-config proxy.conf.json"

我的 app.component.ts 文件是这样的:

  constructor(private http: Http) {
    this.getUsers();
  }

  getUsers(): any {
    return this.http.get("http://localhost:4200/api/getusers")
      .subscribe(response => {
        console.log(response);

      })
  }
Run Code Online (Sandbox Code Playgroud)

在我的 API 中,它提供了一组来自http://localhost:8080/getusers URL 的用户

  • 但是,为什么你需要``http://localhost:4200/api/getUsers'```。尝试提供``this.http.get('api/getUsers')```。 (3认同)