gpt4 book ai didi

typescript - 具有基本安全授权的 Angular 2 调用 API

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:08 24 4
gpt4 key购买 nike

我正在尝试从 Angular 2 客户端调用使用 ASP Web API 实现的 HTTP 方法。我收到了这个错误:

OPTIONS http://endpoint/api/Get?key=something 401 (Unauthorized)

XMLHttpRequest cannot load http://endpoint/api/Get?key=something. 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:4200' is therefore not allowed access. The response had HTTP status code 401.

这是我的实现,当我在 IIS 服务器上禁用基本身份验证时它运行良好:

import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map'
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Entity } from "app/view-models/entity";

@Injectable()
export class HttpService {
headers;
options;
constructor(private _http: Http) {
this.headers = new Headers();
this.headers.append('Authorization', 'Basic ' + btoa('username:password'));
this.headers.append("Access-Control-Allow-Credentials", "true");
this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.options = new RequestOptions();
this.options = new RequestOptions({ headers: new Headers(this.headers) });
}

public Get = (): Observable<Entity> => {
var params = '?key=something';
return this._http.get(environment.apiBaseUrl + environment.getSettings + params
, this.options)
.map(response => <Entity>response.json());
}
}

最佳答案

这看起来更像是 CORS 错误,而不是角度/ typescript 错误。您正试图从“localhost”跨越到“endpoint”。您必须配置端点服务以允许来自该域的请求。

https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

关于typescript - 具有基本安全授权的 Angular 2 调用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44113628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com