为什么Angular Proxy配置对我不起作用?

时间:2019-12-16 16:36:26

标签: angular typescript proxy angular-httpclient

我已经如下配置了proxy.conf.json文件:

{
  "/api/**": {
    "target": "http://192.168.0.50:3000",
    "secure": false,
    "pathRewrite": { "^/api": "" }
  }
}

然后我在package.json中运行以下脚本:

ng serve --proxy-config proxy.conf.json

proxy.conf.json文件位于项目的根目录。

在运行服务器时,我会通过控制台收到此消息。

10% building 3/3 modules 0 active[HPM] Proxy created: /api  ->  http://192.168.0.50:3000

但是在查看我尝试执行的发帖请求时,请忽略规则并使用Angular网址 192.168.0.50:4200

我尝试发送的内容。

this.httpClient.post('/api/test', { 'test': 'test' }).subscribe((response: any) => {
 console.log(response)
});

Angular发送的内容。

Angular shows this error in the console making the post to it.

我该如何解决?

1 个答案:

答案 0 :(得分:0)

我认为您在代理配置中缺少"changeOrigin": true属性,

{
  "/api/**": {
    "target": "http://192.168.0.50:3000",
    "secure": false,
    "changeOrigin": true
    "pathRewrite": { "^/api": "" }
  }
}