HttpClient未设置授权标头

HttpClient未设置授权标头

本文介绍了Angular HttpClient未设置授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了其他几个类似的问题,但是它们并不能解决问题.我使用MailChimp的API进行了简单的调用,以在成员注册时将其添加到我的邮件列表中.

I have seen several other questions like this, but they do not solve the issue. I used MailChimp's API to make a simple call to add a member to my mailing list when they sign up.

但是,当我进行测试时,我得到了未经授权的401,API抱怨没有提交API密钥.当我在Chrome中检查请求时,看不到任何授权"标头.这是我的代码:

However when I test, I get a 401 unauthorized and the API complains of no API key submitted. When I inspect the request in Chrome, I don't see any Authorization header. Here is my code:

        const formData = {
            email_address: this.emailControl.value,
            status: 'subscribed',
            merge_fields: {
                NAME: this.nameControl.value
            }
        };
        const header = new HttpHeaders({
            'Authorization': 'apikey:' + environment.mailChimpApiKey
        });

        this.http.post(this.mailChimpUrl, formData, {
            headers: header,
            observe: 'response'
        }).subscribe(response => {
            console.log('response', response);
            if (response.status === 200) {
                this.submitted = true;
            }
        });

我已经检查并仔细检查了HttpClient.post方法签名,以及MailChimp API如何期望接收Auth标头.看来我做得对,所以Angular为什么不设置标题?

I have checked and double-checked the HttpClient.post method signature, and how the MailChimp API expects to receive the Auth header. It seems like I'm doing everything right, so why isn't Angular setting the header?

我注意到在设置可选标头时,该值仅对Access-Control-Request-Headers更改.我在阅读Chrome控制台时错了吗?

I am noticing that the value changes only for the Access-Control-Request-Headers when I set optional headers. Am I reading the chrome console wrong?

角度版本:5.2.4

Angular version: 5.2.4

推荐答案

问题不在于Angular.现代浏览器会针对大多数跨域请求发送预检选项请求, Mailchimp不支持. Mailchimp API不支持客户端实现:

The issue is not with Angular. Modern browsers send a preflight OPTIONS request for most cross-domain requests, which is not supported by Mailchimp. The Mailchimp API does not support client-side implementations:

如果说得更明显一点会很好,但是我一开始没有注意到.最好的解决方案是使用jsonp.

It would have been nice if this was stated a bit more obviously, but I didn't notice it at first. The best solution is to use jsonp.

这篇关于Angular HttpClient未设置授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:58