【问题标题】:angular 6 httpclient pass credentials in urlangular 6 httpclient在url中传递凭据
【发布时间】:2018-08-02 10:54:19
【问题描述】:

我尝试通过在 URL 中传递凭据来从 angular 6 项目向CouchDB 发出 HTTP GET 请求。但我总是收到 401 错误“您无权访问此数据库。”。

代码如下:

var url = "http://user:password@localhost:1234/mydatabase";
 this.http.get(url)
          .subscribe(
              data => console.log(data),
              error => console.log(error)
          );

我也尝试了{'withCredentials': true} 选项,但得到了同样的错误。

Angular 版本:6.1.0,使用 HttpClient

【问题讨论】:

  • Interceptors 会帮助你。
  • 哪个请求失败了? cors 的 OPTIONS 还是实际的 get 请求?
  • @David:所有请求都失败了,因为 Angular http 没有传递用户名和密码,如果我在 chrome 中检查网络请求,它只是 localhost:1234... 而不是 user:password@localhost:1234。 ..

标签: angular authentication couchdb httpclient angular6


【解决方案1】:

试试下面的代码。从内存中,您不能将 username:password 与 HttpClient 一起使用

const headers = new HttpHeaders(
{
     'Authorization':'Basic '+btoa(`${username}:${password}`)
});

var url = "http://localhost:1234/mydatabase";
 this.http.get(url, {headers})
      .subscribe(
          data => console.log(data),
          error => console.log(error)
      );

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    相关资源
    最近更新 更多