发布请求变为选项请求

时间:2018-06-07 13:33:08

标签: angular typescript request

我的问题在于我的api Angular 6.一旦在发送POST请求时创建了拦截器,这些就会变成OPTIONS请求。

有什么问题?

这是一个服务的代码

import { Injectable } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { AppConfig } from '../app.config';
import { Perfil } from '../Entities/Perfil';
// import { Http } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class UsuariosService {

  constructor(private http: HttpClient, private config: AppConfig) { }

  private per = new Perfil(1);

  getPerfiles() {
    return this.http.post(this.config.apiUrl + 'perfiles/Buscar/', this.per);
  }


}

此图片将帮助我们解决此问题:

enter image description here

问候!

3 个答案:

答案 0 :(得分:1)

这是一个CORS问题,就像lomboboo说OPTIONS是一个特殊的请求,要求服务器询问我该怎么做,我是否可以访问内容?

为了提供修复,您需要在服务器(后端)中实现CORS标头并允许POST以及您需要的任何其他操作。

答案 1 :(得分:0)

//**need to pass header in your post api**


const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

 getPerfiles() {
    return this.http.post(this.config.apiUrl + 'perfiles/Buscar/', this.per,httpOptions).subscribe(result => {
        console.log(result);
      }, error => console.log('There was an error: '));


};
  }

答案 2 :(得分:0)

Yeahhh! 。我知道他们是cors,并且确实在后面实施,但很糟糕。 我实施的解决方案是这样的: (使用.Net Framework 4)

WebApiConfig.cs内部

public static void Register(HttpConfiguration config)
        {

            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
         }

感谢 lomboboo Mike ,这是非常有帮助的!

相关问题