我有一个.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;
});
}
}
感谢您的帮助。...
答案 0 :(得分:2)
您可以在根文件夹中创建一个proxy.conf.json
文件,并将其添加到其中。
{
"/ShoppingCartApi/*" : {
"target" : "http://resturl:8029",
"secure" : "false",
"logLevel" : "debug",
"changeOrigin" : true
}
}
并使用ng serve --proxy-config proxy.config.json
答案 1 :(得分:-1)
解决方案可以是HttpInterceptor,如下所述: https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8
答案 2 :(得分:-1)
从邮递员看来,这可能是因为您的api正在接受原始内容以传递apikey。从角度来看,您将其作为json对象传递。
请尝试将其作为字符串传递以查看其工作原理。
CORS设置也是您需要在后端api上检查的内容。