【问题标题】:angular http retrieve data with post request带有发布请求的角度http检索数据
【发布时间】:2019-06-24 23:14:38
【问题描述】:

我有一个完美运行的 .net backback。但是当我将它与角前端连接时,我遇到了这个问题。后端所有请求都是发布请求。需要在每个请求的正文中传递一个 ApiKey。使用邮递员可以完美运行。

错误:

邮递员:

resetService.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class RestService {

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

  constructor(private http: HttpClient) {
    console.log(this.httpOptions);
  }

  getProductCategories(): Observable<any> {
    return this.http.post<any>('http://restUrl:8029/ShoppingCartApi/GetProductList', this.apiKey, this.httpOptions);
  }

}

soap.component.ts

import { Component, OnInit } from '@angular/core';
import { RestService } from 'src/app/services/rest.service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-soap',
  templateUrl: './soap.component.html',
  styleUrls: ['./soap.component.css']
})
export class SoapComponent implements OnInit {

  products: any = [];

  constructor(public rest: RestService, private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    this.getProducts();
  }

  getProducts() {
    this.products = [];
    this.rest.getProductCategories().subscribe((data) => {
      console.log(data);
      this.products = data;
    });
  }

}

任何帮助表示赞赏....

【问题讨论】:

  • 从外观上看,你需要在你的服务器上启用CORS,另外,不要在网上发布你的私钥
  • 您需要启用 CORS 或者使用 Angular 的代理来使用您的后端,您只需添加一个文件来指定如何在 DEV 模式下使用代理。 Angular-cli proxy usage
  • 谢谢,这不是原始密钥..但我无法更改服务器端。 CORS 也显示在标题中。
  • 如果你不能改变服务器的东西,那么你可能无法做到这一点,除非你能以某种方式欺骗你的服务器认为来源是相同的
  • @NguyenPhongThien 如果 CORS 未启用且原始 url 不匹配服务器,则任何请求都会发生 CORS 问题

标签: angular typescript rest cors


【解决方案1】:

您可以在根文件夹中创建一个proxy.conf.json 文件并将此内容添加到其中。

{
  "/ShoppingCartApi/*" : {
    "target" : "http://resturl:8029",
    "secure" : "false",
    "logLevel" : "debug",
    "changeOrigin" : true
  }
}

并使用ng serve --proxy-config proxy.config.json提供服务

【讨论】:

    【解决方案2】:

    【讨论】:

    • 对不起,我不知道如何使用它,
    【解决方案3】:

    从邮递员看来,这可能是因为您的 api 正在接受用于传递 apikey 的原始内容。从角度,您将其作为 json 对象传递。

    请尝试将其作为字符串传递以查看它是否有效。

    CORS 设置也是您需要在后端 api 上检查的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2016-01-12
      • 2022-02-07
      • 2012-11-08
      相关资源
      最近更新 更多