角度2 HttpPost到Oauth2

时间:2017-08-01 17:51:34

标签: angular ionic-framework oauth oauth-2.0 ionic2

我正在做HttpPost而且正在给我error 401,但我在StackOverflow上搜索了很多,我猜我的电话没问题,但是问题是当我在HttpPost上执行此ARC时,如果我不放authorization: user:password,它会弹出一条消息说明:

enter image description here

我必须手动,,即使我这样做了:

enter image description here

会弹出Authentication required

它会自动更改为

  

授权:基本JvbnyZpZpzZWNTcHNQX =

现在,代码看起来像这样:

我的标题

 private headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
 private apiUrl = 'https://myApiTest/oauth/token';




var auth = "Basic " + Base64.encode("test:test");//Also have tried to copy the hexgenerated by ARC
    this.headers.append('authorization', auth);
    var body = 'grant_type=password&username=test@test.com&password=test';
     return new Promise((resolve, reject) => {
      this.http.post(this.apiUrl,body, {
            headers: this.headers
          })
        .subscribe(res => {
          alert(res.json());
          resolve(res.json());
        }, (err) => {
          reject(err);
          console.log(err);
        });
    });

这是控制台

给出的错误
  

XMLHttpRequest无法加载https://myApiTest/oauth/token。预检的响应具有无效的HTTP状态代码401   选项https://myApiTest/oauth/token 401()

修改

我已经在我的Android上构建了它并且工作正常似乎是谷歌Chrome的一个问题,我发现使用它:C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:/Chrome dev session2" --disable-web-security但我想使用其他方式。

2 个答案:

答案 0 :(得分:2)

我最初的猜测是API不允许跨域请求(CORS)更多关于CORS - > CORS

您可能需要在API中添加中间件以允许CORS 可能会在此处设置一些标头 如果您使用的是节点API,则可能需要设置标题。

res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,OPTIONS');

答案 1 :(得分:0)

您需要启用CORS。

serverhttps://myApiTest)和client requests

最后,我不建议您禁用浏览器安全性,这应该是您的最后手段。

干杯!