为什么在localhost中使用Angular时,http请求无法加载资源?
我有一个ASP.NET MVC项目,它使用ASP.NET WebAPI和Angular作为UI组件。我对Angular相当陌生,所以请耐心等待。下面是我的项目中的配置文件。为什么在localhost中使用Angular时,http请求无法加载资源?
package.json
文件
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "concurrently \"npm run build:watch\" \"npm run serve\"",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@angular/common": "~4.3.4",
"@angular/compiler": "~4.3.4",
"@angular/core": "~4.3.4",
"@angular/forms": "~4.3.4",
"@angular/http": "~4.3.4",
"@angular/platform-browser": "~4.3.4",
"@angular/platform-browser-dynamic": "~4.3.4",
"@angular/router": "~4.3.4",
"angular-in-memory-web-api": "~0.3.0",
"systemjs": "0.19.40",
"core-js": "^2.4.1",
"rxjs": "5.0.1",
"zone.js": "^0.8.4"
},
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "~2.1.0",
"canonical-path": "0.0.2",
"tslint": "^3.15.1",
"lodash": "^4.16.4",
"jasmine-core": "~2.4.1",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~4.0.14",
"rimraf": "^2.5.4",
"@types/node": "^6.0.46",
"@types/jasmine": "2.5.36"
},
"repository": {}
}
systemjs.config.js
文件
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
//baseURL: '/',
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
//meta: {
// './*.js': {
// loader: 'systemjs-angular-loader.js'
// }
//},
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
main.ts
文件
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';
// Enable production mode unless running locally
//if (!/localhost/.test(document.location.host)) {
// enableProdMode();
//}
platformBrowserDynamic().bootstrapModule(AppModule);
app.routing.ts
文件
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './Components/home.component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
app.module.ts
文件
import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { HomeComponent } from './Components/home.component';
import { ChangeService } from './Services/changes.service';
@NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, routing],
declarations: [AppComponent, HomeComponent],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }, ChangeService],
bootstrap: [AppComponent]
})
export class AppModule {}
changes.service.ts
文件
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
@Injectable()
export class ChangeService {
constructor(private _http: Http) { }
get(url: string) {
return this._http.get(url);
}
}
app.component.ts
文件
import { Component, ElementRef, OnInit } from '@angular/core';
import { ChangeService } from './Services/changes.service';
@Component({
selector: 'moc-landing',
templateUrl: './app/Components/home.component.html',
styleUrls: ['./app/Components/home.component.css']
})
export class AppComponent implements OnInit {
maintitle: string;
statusList: IStatus[];
showByList: IShowBy[];
msg: string;
constructor(private elementRef: ElementRef, private _changeService: ChangeService) {
this.maintitle = this.elementRef.nativeElement.getAttribute('maintitle');
}
ngOnInit() {
this.LoadStatus();
this.LoadShowBy();
}
LoadStatus(): void {
this._changeService.get('http://localhost:56534/api/MoC/GetStatuses').subscribe(response => { this.statusList = response.json(); });
}
LoadShowBy(): void {
this._changeService.get('http://localhost:56534/api/MoC/GetShows').subscribe(response => { this.showByList = response.json(); });
}
}
而且在我WebApiConfig.cs
,内部的静电Register
方法,我也更新routeTemplate
如下。
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我的问题是,当我运行从Visual Studio 2017年上http://localhost:5653的应用;我得到Failed to load resource: the server responded with a status of 400 (Bad Request)
我直接在浏览器的地址栏http://localhost:56534/api/MoC/GetStatuses
测试http
请求,它给我的json
数据,我需要。所以,在WebAPI方面没有问题。
我发现这个SO post,并试图遵循Praveen M答案,但它并没有为我工作。
为什么我得到(400)错误的请求?,我错过了app.routing.ts
中的重要配置吗?
请问,任何人在这里心地善良可以给我一个硬币?
尝试改变:
providers: [{ provide: APP_BASE_HREF, useValue: '/' }, ChangeService]
只是:
providers: [ChangeService]
好吧,我试过了,但仍然没有工作:( – Juniuz
好了,敲我的头挂在墙上后。我发现了这个问题的罪魁祸首。这是我的一个愚蠢的错误。这个问题不在与本地主机无关的http请求上。它是组件元数据templateUrl
之一。我错误的声明像这样templateUrl: '<span>Hello</span>'
,而不是仅仅template: '<span>Hello</span>'
这就是为什么应用程序将引发异常,因为组件模板是在恶劣形式http://localhost:56534/%0A%20%20%20%20
_.subscribe(节目=> {this.showByList =显示},错误=> this.msg =错误); _为什么订阅逗号? –
@RahulSingh无所谓了。我已将该行更改为此this._changeService.get('http:// localhost:56534/api/MoC/GetShows').subscribe(response => {this.showByList = response.json();}); '但我仍然得到了Http 400的错误请求。 – Juniuz
从组件调用中删除.json,您已经在服务 –