【问题标题】:API working from Postman, but getting error when posting from Angular使用 Postman 的 API,但从 Angular 发布时出错
【发布时间】:2022-01-06 03:12:52
【问题描述】:

我有一个来自 Postman 的 POST,效果很好,但是当我通过 Angular 发布时,我得到:

[错误] 由于访问控制,XMLHttpRequest 无法加载 (DOMAIN) 检查。

在这里和谷歌检查了几个答案后,我想出了更改 web.config 和 express 以启用 CORS。

NODE 应用程序托管在 IIS 上,我已经将 customHeaders 添加到 web.config:

<customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
 <add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>

Angular 代码非常简单:

let APIURL = sessionStorage.getItem('endPoint') + "outside/login";
    let options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
    let body: any = this.payLoad;
    this.httpClient.post(APIURL, JSON.stringify(body), options).subscribe(
      result => {
          .....
          .....
          .....
})

我也加了

app.options('*', cors())

到 Express 但仍然收到此错误。

当我在远程服务器上使用 IP 地址和端口 3000 时,这非常有效。当我通过 IIS 设置域并设置 URL 重写时,一切都崩溃了。

我想特别强调这一点:它在 Postman 上完美运行,但在应用程序(本地主机或 Web 服务器)中崩溃。

谢谢。

更新:当停止 PM2 和停止 IIS 网站时,当然 Postman 不起作用,但 Angular 检索到相同的错误,所以我倾向于认为问题出在 Angular 级别(?)。

这是 IIS 的重写规则

 <rewrite>
    <rules>
        <rule name="ReverseProxyInboundRule1" stopProcessing="true">
            <match url="(.*)" />
            <action type="Rewrite" url="http://localhost:3000/{R:1}" />
        </rule>
    </rules>
</rewrite>

【问题讨论】:

    标签: node.js angular iis cors


    【解决方案1】:

    将此添加到您需要 express 的 js 文件中。我假设您需要 CORS。如果没有:

    const cors = require('cors')
    

    然后

    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
      });
    

    并摆脱 web.config 中的 customHeaders。您设置了两次标题。

    <customHeaders>
     <add name="Access-Control-Allow-Origin" value="*" />
     <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
     <add name="Access-Control-Allow-Headers" value="Content-Type" />
    </customHeaders>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 2021-01-21
      • 2019-07-29
      • 2016-09-02
      相关资源
      最近更新 更多