【问题标题】:Angular/Ionic CORS error with Authorization header带有授权标头的 Angular/Ionic CORS 错误
【发布时间】:2019-03-20 07:54:36
【问题描述】:

我正在构建一个 Ionic 应用程序(角度 4),我想使用一个在 IIS 10 上使用 C# 构建的 API。

一开始这样的 POST 请求是什么时候:

this.http.post(my_url, my_credentials, { headers = new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
  })
});

我收到一条 错误 404 消息:

Failed to load https://some_url/api/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

经过一些研究,我添加了web.config

access-control-allow-origin: *  

这解决了 CORS 问题。

之后我检索了我的访问令牌并想将其用于其他请求
所以我用 authorization header 发出了另一个帖子请求:

this.http.post(my_url, my_body, { headers = new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer ' + token
  })
});

然后我得到了和以前一样的错误。

所以,总而言之,这些请求都在同一个应用程序上。第一个请求很好,但第二个不行。

为了接受额外的 Authorization 标头,必须在服务器上添加什么额外配置?

【问题讨论】:

    标签: angular ionic-framework cors http-headers iis-10


    【解决方案1】:

    尝试添加到 web.config:

    Access-Control-Allow-Methods: POST, GET (..and more Methods that you need.)
    Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
    

    我不确定它是否会起作用,但你可以试试看:P

    【讨论】:

      【解决方案2】:

      您可能想要添加 proxy.conf.json 以将您的应用程序 URL 重定向到适当的服务器 URL。以下文章可能会有所帮助: https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/

      【讨论】:

        【解决方案3】:

        我使用并为 asp.net 核心后端工作

        const headers = new HttpHeaders()
           .set('Content-Type', 'application/json')
           .set('Accept', 'application/json')
           .set('Authorization', 'Bearer ' + token); 
        
        this.http.post(my_url, my_credentials, headers)
        

        不记得这是否对http有效,我认为它仅对httpClient有效

        【讨论】:

          猜你喜欢
          • 2020-01-05
          • 2019-05-30
          • 2014-12-25
          • 1970-01-01
          • 2017-03-07
          • 2021-02-21
          • 2016-12-28
          • 2018-07-22
          • 2022-01-06
          相关资源
          最近更新 更多