0

不知道我在这里做错了什么。代码非常简单。

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

import { Observable } from 'rxjs/Rx';

@Injectable()
export class Service {

  private baseUrl = 'http://localhost:8443';

  constructor(private http: HttpClient) { }

  callSecurityGateway(): Observable<String> {

    const params = new HttpParams()
    .set('grant_type', 'password')
    .set('scope', 'read')
    .set('username', 'myusername')
    .set('password', 'mypassword');

    const headers = new HttpHeaders().set('Authorization', 'Basic s89s89s89asd');

    const httpOptions = {
      headers: headers,
      params: params,
      responseType: 'text',
      // withCredentials: true
    };

     // this works to ram the parameters in
    // const oauthUrl = '/oauth/token?grant_type=password&scope=read&username=myusername&password=mypassword';
    // return this.http.post<String>(this.baseUrl + oauthUrl, httpOptions);
    return this.http.post<String>(this.baseUrl + '/oauth/token', httpOptions);

   }

}

我在请求标头中看到的是:

OPTIONS /oauth/token HTTP/1.1
Host: localhost:8443
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, 
like Gecko) Chrome/62.0.3202.89 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

我什至没有看到任何应该有的参数。

我不知道这是否有帮助,但我在httpOptions控制台中的对象中看到的内容显示了标题headers.lazyUpdate和参数,params.updates其中是我设置的 4 个参数的数组。

我的例子已经用完了;http认为向后退并使用而不是httpclient为此可能更容易。

4

1 回答 1

0

如果AuthorizationHeader 不允许出现,您将收到错误消息Access-Control-Allow-Headers。如果您没有,则不会发送诸如 cookie 之类的凭据Access-Control-Allow-Credentials: true

在您的服务器端,尝试添加此代码以使“凭据”在跨站点上工作:

header('Content-Type: text/plain');
if( isset($_SERVER['HTTP_ORIGIN']) )
{
    header('Access-Control-Allow-Origin: ' . trim($_SERVER['HTTP_ORIGIN']));
}else{
    header('Access-Control-Allow-Origin: *');
}
header('Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Credentials: true');

// Client/Browser may send 'OPTIONS' header to check its allowed or not
if( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' )
{
    return;
}
于 2018-02-04T09:40:47.543 回答