Angular不安全的HTTP请求

时间:2019-01-15 16:46:43

标签: asp.net angular asp.net-core angular7

我正在尝试与Angular一起学习ASP.NET Core,并且有一个基本的项目启动。现在,我遇到了一个非常基本的问题,我需要进行一些修改。我创建了一个Web api项目并将其托管在 IIS -内部服务器中。因此,我在Angular中按如下方式使用了api:

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
    title = 'Our First Angular App';
    public values: object[];

    constructor(private http: Http) {
      this.http.get('http://192.168.10.100/api/values').subscribe(result => { //Calling the web api here as jSon
        this.values = result.json() as object[];
        }, error => console.error(error));
    }
}

上面的内容没有在Angular的前端获取数据。相反,使用浏览器的inspect元素进行调试时会抛出异常:

http://192.168.10.100/api/values - http request was insecure

我可以理解,可能需要集成https或某种安全性。但是目前,有什么办法可以使上述代码与http请求一起工作?我将以下配置文件包括在内,如果有帮助的话:

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "OurFirstAngularApp": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "wwwroot",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "C:\\Users\\AT\\Documents\\Visual Studio 2017\\Projects\\OurFirstAngularApp\\OurFirstAngularApp\\node_modules\\bootstrap\\dist\\css\\bootstrap.min.css"
            ],
            "scripts": [
              "C:\\Users\\AT\\Documents\\Visual Studio 2017\\Projects\\OurFirstAngularApp\\OurFirstAngularApp\\node_modules\\bootstrap\\dist\\js\\bootstrap.min.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "OurFirstAngularApp:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "OurFirstAngularApp:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "OurFirstAngularApp:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "OurFirstAngularApp-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "OurFirstAngularApp:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "OurFirstAngularApp:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "OurFirstAngularApp"
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

NB :上面的api在请求时可以正常工作,我的意思是完美地获取jSon数据。

更新1 :Startup.cs

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, 
    // visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

        app.UseDefaultFiles();
        app.UseStaticFiles();
        //app.Run(async (context) =>
        //{
        //  await context.Response.WriteAsync("Hello World!");
        //});
    }
}

更新2 jSon数据-Raw jSon Data

现在我明白了。基本上,它是进行http调用,并且出于安全原因,它需要https。因此,我尝试了一个包含原始jSon数据的https服务。但是,当我完成以下操作后:

public default: object[];

constructor(private http: Http) {
    this.http.get('https://jsonplaceholder.typicode.com/todos/1/').subscribe(result => {
        this.default = result.json() as object[];
    }, error => console.error(error));
}

最后在Angular的前端:

<tr *ngFor="let value of default">
   <td>{{ value.userId }}</td>
   <td>{{ value.title }}</td>
</tr>

当使用浏览器的inspect元素时,以上内容引发了异常,如下所示-错误:找不到类型为'object'的其他支持对象'[object Object]'。 NgFor仅支持绑定到数组等Iterable。

2 个答案:

答案 0 :(得分:1)

尝试在显示循环中使用Elvis运算符:

<tr *ngFor="let value of default">
   <td>{{ value?.userId }}</td>
   <td>{{ value?.title }}</td>
</tr>

?.之后的item(在这种情况下为value)确保Angular不会尝试渲染数据,直到数据显示出来。 ,因此value?.userId会在value.userId失败的地方工作,因为在渲染视图时未定义值,并且Angular在获取完成之前不了解.userID属性,直到它被抛出错误。

另外,当使用http和result.json()时,您将获得一个数据对象数组,因此不需要作为object [];我也倾向于将值键入为any [],看看是否行不通。

public values: any[];

constructor(private http: Http) {
  this.http.get('http://192.168.10.100/api/values').subscribe(result => { //Calling the web api here as json
    this.values = result.json();
    }, error => console.error(error));
}

答案 1 :(得分:0)

您可以在服务器端代码中启用跨域,这对您尝试该功能很有用