Angular 2 HttpPost to Oauth2

2019-03-06 18:55发布

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 :

enter image description here

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

enter image description here

It will pop up the Authentication required.

And it automatically changed to something like

authorization: Basic JvbnyZpZpzZWNTcHNQX=

And now, the code looks like this :

My headers

 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);
        });
    });

And this is the error given by console

XMLHttpRequest cannot load https://myApiTest/oauth/token. Response for preflight has invalid HTTP status code 401 OPTIONS https://myApiTest/oauth/token 401 ()

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.

2条回答
forever°为你锁心
2楼-- · 2019-03-06 19:44

You need to enable CORS.

In your server (https://myApiTest) and also your client requests.

Finally, I do not recommend you to disable the browser security, that should be your last resort.

Cheers!

查看更多
放荡不羁爱自由
3楼-- · 2019-03-06 19:50

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

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');

查看更多
登录 后发表回答