$http.post 发送授权标头

G-M*_*Man 1 angularjs

我正在尝试通过 $http.post 调用传递授权标头到 .NET Web API 服务。

如果我用这个:

$http.post(urls.getEmployeeInfo,
        {
            withCredentials: true,
            headers:{ 'Authorization':  'Basic ' + btoa(username + ":" + password)}
        }
    );
Run Code Online (Sandbox Code Playgroud)

授权标头不会发送到我的服务。

以下作品:

$http({
            url: urls.getEmployeeInfo,
            method: "POST",
            withCredentials: true,
            headers: {
                'Authorization': 'Basic ' + btoa(username + ":" + password)
            }
        });
Run Code Online (Sandbox Code Playgroud)

为什么 $http.post 不发送授权标头?

谢谢

DRo*_*son 6

$http仅接受一个参数:config[文档]

$http.post接受三个参数:url, data, (和一个可选的)config[文档]

因此,如果您想传递配置选项(例如标头),则需要将它们作为第三个参数而不是第二个参数发送:

$http.post(urls.getEmployeeInfo, postData,
    {
        withCredentials: true,
        headers:{ 'Authorization':  'Basic ' + btoa(username + ":" + password)}
    }
);
Run Code Online (Sandbox Code Playgroud)