由于缺少标头,对Jira REST API的预检请求失败

时间:2018-10-14 10:02:35

标签: angular http-headers jira-rest-api

我正在尝试构建将与Jira REST API交互的Angular 6应用程序。

根据控制台,由于缺少标头(Access-Control-Allow-Origin),我对身份验证的POST呼叫对预检请求(OPTIONS)失败。

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5555' is therefore not allowed access.

我认为我没有正确添加标题。

这是我的代码:

export class AuthenticationService {

  readonly headerDict = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Origin': '*'
  };

  readonly baseUrl: string = 'https://jira.domain.com'; //not the actual domain, duh

  constructor( private http: HttpClient ) {
  }

  login( username: string, password: string ): Observable<any> {
    const token: string = window.btoa( `${username}:${password}` );
    window.localStorage.setItem( 'currentUser', JSON.stringify( { authtoken: token } ) );
    const _headers: HttpHeaders = new HttpHeaders( this.headerDict );
    _headers.append( 'Authorization', JSON.stringify(token) );
    const requestOptions = {
      headers: _headers
    };
    return this.http.post<any>( `${this.baseUrl}/rest/auth/1/session`, {}, requestOptions );
  }

  logout() {
    localStorage.removeItem( 'currentUser' );
  }
}

我认为我添加的Headers错误,因为在实际的POST中在requestOptions上放置一个断点时,我看到以下内容: (see here)

对我来说,这似乎并不正确。

1 个答案:

答案 0 :(得分:0)

尝试通过这种方式附加新标题:

const _headers: HttpHeaders = new HttpHeaders( this.headerDict );
_headers = _headers.set( 'Authorization', JSON.stringify(token) );

希望这会有所帮助。