预检的响应具有无效的HTTP状态代码400角度删除

时间:2017-11-07 11:28:56

标签: angular asp.net-web-api

当我尝试以角度调用delete方法时,我收到了以下错误。

  

无法加载http://localhost:56065/api/Regists/5:响应   预检具有无效的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);
    });

  }
}

3 个答案:

答案 0 :(得分:1)

尝试将服务用于这些类型的东西,组件对于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);
})
      }

    }

只需拨打服务方式:

this.service.delete(this.deletedData).subscribe(res => {
          console.log('deleted Success');
          console.log(res);
        }

答案 1 :(得分:0)

您必须在服务器上启用cors尝试关注您的网络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();
        }

答案 2 :(得分:0)

尝试使用以下代码

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

}