【问题标题】:http POST in angular 2 client not working while http GET is workinghttp GET 工作时,angular 2 客户端中的 http POST 不工作
【发布时间】:2017-11-14 13:47:19
【问题描述】:

我正在尝试在 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());
     }
    
 }

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

【问题讨论】:

  • 您使用的是什么服务器?您使用的是 Angular 开发服务器还是某种生产服务器?如果您使用的是 Angular 2,是否可以升级到较新的版本 (5) 并查看是否可行?

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以在 get 调用中使用 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){.....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2019-11-19
      • 1970-01-01
      • 2019-06-18
      • 2012-12-11
      • 2015-09-14
      • 1970-01-01
      相关资源
      最近更新 更多