Angular 飞行前响应的HTTP状态代码无效
当我尝试在angular中调用Angular 飞行前响应的HTTP状态代码无效,angular,asp.net-web-api,Angular,Asp.net Web Api,当我尝试在angular中调用delete方法时,我收到了下面的错误 未能加载:的响应 飞行前的HTTP状态代码400无效 这是我的component.ts文件 import { Component, OnInit } from '@angular/core'; import { Http ,RequestOptions,Headers} from '@angular/http'; @Component({ selector: 'app-table', templateUrl: './
delete
方法时,我收到了下面的错误
未能加载:的响应
飞行前的HTTP状态代码400无效
这是我的component.ts文件
import { Component, OnInit } from '@angular/core';
import { Http ,RequestOptions,Headers} from '@angular/http';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
reId;
options: RequestOptions;
header: Headers;
constructor(private http:Http) { }
ngOnInit() {
}
onCli(){
this.header = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
this.options = new RequestOptions({ headers: this.header });
this.http
.delete('http://localhost:56065/api/Regists/'+this.reId.toString(),this.options)
.subscribe(res => {
console.log(res);
},
error => {
console.log(error);
});
}
}
您必须在服务器上启用cors,请在web api的
Global.asax.cs
文件中尝试以下操作
protected void Application_BeginRequest()
{
if (Context.Request.HttpMethod != "OPTIONS") return;
Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,x-access-token");
Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
Context.Response.End();
}
试试下面的代码
onCli(){
this.header = new Headers({
'Content-Type': 'application/json'
});
this.http
.delete('http://localhost:56065/api/Regists/'+this.reId.toString(),{headers: this.header})
.subscribe(res => {
console.log(res);
},
error => {
console.log(error);
});
}
尝试将服务用于此类内容,组件对于http请求来说并不完全舒适 尝试提供服务:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class tableService {
private serverUrl:string= "http://localhost:56065/api/Regists/";
private headers=new Headers({
});
constructor (
private http: Http
) {
this.headers.append('Accept', 'application/json');
this.headers.append('Authorization', 'if token');
this.headers.append('Access-Control-Allow-Origin','*');
return headers;
}
delete(data: any): Observable<any>{
let url = this.serverUrl + '/' + data.id;
return this.http.delete(url,{headers: this.headers}).map(res => res.json()).catch(err => {
return Observable.throw(err);
})
}
}
您是否在rest api端启用了cors?是的,我已经启用了corsHow。你能告诉我OP使用的是哪一个服务器端软件包吗?@bcs他在他的问题标签中添加了asp.net-web-api。实际上我想使用组件。有什么建议吗?你启用了CORS吗?从angularjs启用/设置CORS对你没有帮助。你需要在后端代码中启用。或者你可以使用
this.service.delete(this.deletedData).subscribe(res => {
console.log('deleted Success');
console.log(res);
}