Angular的不安全HTTP请求



我正在尝试用ASP.NET Core学习Angular,并启动了一个基本的项目。现在,我遇到了一个非常基本的问题,我想,需要进行一些修改。我创建了一个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"
]
}
}

N.B:当请求时,上面的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!");
//});
}
}

更新2jSon数据-原始jSon数据

现在我明白了。基本上它是在进行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只支持绑定到数组等可伸缩对象

尝试在显示循环中使用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()时,您将获得数据对象的单个数组,因此不需要as object[];我也倾向于将值键入任意[],看看这是否不起作用。

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));
}

您可以在服务器端代码中启用交叉源代码,这将对您尝试非常有用

最新更新