在angular.json文件中配置proxy.conf.json文件,使其显式地支持POST方法。
步骤1:创建一个proxy.conf.json文件,代码如下:
{ "/api/*": { "target": "http://localhost:3000", "secure": false, "logLevel": "debug", "changeOrigin": true, "pathRewrite": { "^/api": "" }, "protocolRewrite": "http" } }
此配置将“/api/”中的任何请求都重定向到“http://localhost:3000”下的相应接口。这里“/”是通配符,表示不管api后面跟的是什么,都会被重定向。
步骤2:在angular.json文件中添加配置,让Angular应用支持代理。
{ "projects": { "project-name": { //... "architect": { "serve": { "options": { //... "proxyConfig": "src/proxy.conf.json" } } } } } }
在上面的代码中,“project-name”指的是你的Angular项目名。我们把代理配置文件路径指定为“src/proxy.conf.json”。
步骤3:最后,在我们的服务中调用POST请求,就能够完美工作了,例如:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http';
@Injectable() export class DataService { constructor(private http: HttpClient) { }
get() {
return this.http.get('/api/data');
}
post(data) {
return this.http.post('/api/data', data);
}
}
这样,在调用post请求时,就会被代理到我们配置的接口上了。