1.在跟目录创建proxy.config.json文件
{ "/api": { "target": "http://localhost:3000", "secure": false, "changeOrigin": true, "pathRewrite": {"/api" : ""} } }/api直接在get中使用代表代理,后面跟路径。例如:/api/ 代表跟路径。 pathRewrite的作用,发送请求时候,会发送http://localhost:3000/api/的形式,他的作用就是取代/api用空格,发送就变成了http://localhost:3000/
2.在angular.json文件中配置
- "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "chart:build", "proxyConfig": "proxy.config.json" }, 添加proxyconfig
3. package.json配置文件
"scripts": { "ng": "ng", "start": "ng serve --proxy-config proxy.config.json", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" },为start添加代理配置,使用代理启动 启动 ng run start
4. 使用
发送get请求。例:http.get('/api/'); 跟路径
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did222968