【发布时间】:2017-07-09 09:25:08
【问题描述】:
8080 – 托管后端的端口 4200 - 我的 Angular2 前端
在我的 Angular2 项目中,我的文件 proxy.config.json 包含这样的内容
{
"/api": {
"target": "http://localhost:8080",
"secure": false,
"changeOrigin": "true",
"pathRewrite": {"^/api": ""}
}
}
在 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);
})
}
我收到http://localhost:4200/api/getusers 404(未找到)的错误。正如我们所看到的,没有任何东西被代理。为什么?我是不是做错了什么?
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
这是浏览器控制台响应:
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…}
【问题讨论】:
-
您是否尝试过使用完整 URL localhost:4200/api/getusers 而不是 /api/getusers
-
我的后端托管在 localhost:8080/api 这就是为什么我使用代理设置,并且 localhost:8080/api/getusers 工作正常。
-
控制台输出是什么?
-
我添加了有问题的控制台输出
-
你找到解决方案了吗?
标签: angular angular-cli http-proxy