当http GET正在工作时,角度2客户端中的http POST无法正常工作

时间:2017-11-14 13:47:19

标签: angular http post asp.net-core-2.0

我正在尝试在angular 2客户端(asp.net core 2.0 api服务器)上执行http POST请求。

起初有一个415 error (Unsupported Media)

当我添加标题时,会出现response to preflight request doesn't pass access control check: No 'Access-Control-Origin' header is present on the requested resource错误。

同一服务中的Http GET工作正常(没有标题)。



import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

export class MyService {

  constructor(private http: Http) {}
  
    // This is working
    getStudents(): Observable <string[]>{
      return this.http.get('https://localhost:44753/api/students', {withCredentials:true})
        .map((res:Response)=> res.Json());
    }
    
    // Return 415
    getStudent(name): Observable <string[]>{
    let data = {
      "name": name
    }
      return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data),          {withCredentials:true})
        .map((res:Response)=> res.Json());
    }
    
    // Return 401
     getStudent2(name): Observable <string[]>{
      let data = {
        "name": name
      }
    
      let headers = new Header();
      headers.append('Content-Type', 'application/json);
      headers.append('Access-Control-Allow-Origin', '*');

      let options = new RequestOptions({ headers:headers , withCredentials:true });

        return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data),          options)
          .map((res:Response)=> res.Json());
     }
    
 }
&#13;
&#13;
&#13;

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

您似乎需要为CORS请求配置服务器。

答案 1 :(得分:0)

您可以在get call

中使用SearchParams代替标头
    public getStudent = (name: string): Observable<string[]> => {

    let params: URLSearchParams = new URLSearchParams();
    params.set('name', name);
    this.options.params = params;

    return this.http.get('https://localhost:44753/api/students', this.options)
        .map(
        data => data.json()
        );
};

还要仔细检查您是否期望单个字符串而不是字符串[]

并通过[HttpGet(“{name}”)装饰]你的WebApi方法

[HttpGet("{name}")]
public List<string> Students (string name){.....