角度2 HttpPost到Oauth2 [英] Angular 2 HttpPost to Oauth2

查看:961
本文介绍了角度2 HttpPost到Oauth2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个 HttpPost 并且给我错误401 但我搜索了很多 StackOverflow 我猜我的电话没问题,但问题是当我在<$ c $上执行 HttpPost 时c> ARC 如果我没有输入授权:user:password 它会弹出一条消息说明:

I'm doing an HttpPost and is giving to me error 401 but I've searched a lot on StackOverflow and I guess my call is OK, but the problem is when I execute this HttpPost on my ARC if I do not put the authorization: user:password it will popup a message saying this :

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

And I have to put it manually, BUT even if I do this :

< img src =https://i.stack.imgur.com/m40C0.jpgalt =在此处输入图像说明>

它将会弹出需要验证

并自动更改为


授权:基本Jvbn yZpZpzZWNTcHNQX =

authorization: Basic JvbnyZpZpzZWNTcHNQX=

现在,代码如下所示:

My标题

 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 ()

XMLHttpRequest cannot load https://myApiTest/oauth/token. Response for preflight has invalid HTTP status code 401 OPTIONS 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 但我想使用其他方式。

EDIT

I've build it on my Android and it works fine seems like a problem with Google Chrome, I've found to use this : C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:/Chrome dev session2" --disable-web-security but I'd like to use other way.

推荐答案

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

My initial guess would be that the API doesn't allows a cross domain request(CORS) More on CORS -> CORS

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

You might need to add middle ware to your API to allow CORS There might be some headers to set here If you are using a node API you might wanna set headers.


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

这篇关于角度2 HttpPost到Oauth2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆