【发布时间】: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