Proxy configuration did not working with angular CLI
8080 –后端托管的端口
4200 –我的Angular2前端
在我的Angular2项目中,我有一个文件proxy.config.json,内容如下
1 2 3 4 5 6 7 8 | { "/api": { "target":"http://localhost:8080", "secure": false, "changeOrigin":"true", "pathRewrite": {"^/api":""} } } |
在Angular2 package.json中,我将启动过程更改为
当我在Commander
我正在尝试发送请求(Angular2)
1 2 3 4 5 6 7 8 9 10 | 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代码的控制台输出为
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
这是浏览器控制台响应:
1 2 3 | 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>Apache Tomcat/7.0.47 - Error re…hade">Apache Tomcat/7.0.47</body></html>", status: 404, ok: false, statusText:"Not Found", headers: Headers…} |
我已经尝试过这种方式。
我的proxy.conf.json文件是这样的:
1 2 3 4 5 6 7 8 | { "/api": { "target":"http://localhost:8080", "secure": false, "changeOrigin":"true", "pathRewrite": {"^/api":""} } } |
并且我用package.json中的
我的app.component.ts文件是这样的:
1 2 3 4 5 6 7 8 9 10 11 | constructor(private http: Http) { this.getUsers(); } getUsers(): any { return this.http.get("http://localhost:4200/api/getusers") .subscribe(response => { console.log(response); }) } |
in my API it provides set of user from http://localhost:8080/getusers
URL
使用它,一切正常。
1 2 3 4 5 6 7 8 9 10 | { "/api/*": { "target":"https://172.16.2.10", "secure": false, "pathRewrite": { "^/api/*":"" }, "changeOrigin": true } } |
尝试
{
" / api / *":{
" target":" http:// localhost:8080",
"安全":错误
}
}