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

标签 typescript asp.net-web-api2 angular2-services angular2-http

我正在尝试从 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/

相关文章:

angular - 类型 'Observable<string[]>' 缺少类型 'string[]' 的以下属性 : length, pop、push、concat 和另外 25 个

c# - 尝试将浮点解析为 int 时,Web API 2 中的 Newtonsoft JSON 反序列化无提示地失败

c# - 不存在的目录/文件 Web API(不是 Controller )的自定义错误页面

Angular 2 RC 2 使用移动手势(滑动、捏合、旋转)

Angular - 警告 : Entry point '@libray-package' contains deep imports into 'module/file'

node.js - 如何将 'import' 第三方 Javascript 文件写入 IntelliJ,以便我可以在 Typescript 文件中引用它

angular - 如何从服务中调用组件方法? ( Angular 2)

angular - 在angular2中使用订阅调用成功,错误回调?

reactjs - 我可以在不知道 sliced reducer 路径的情况下编写选择器吗?

kendo-ui - 使用 Web API 2 Controller 的 Kendo Grid MVC 包装器示例