[英]My ionic3 code prompts for these errors when making an http request
如果我的http发布请求未添加body参数,则该请求完全正常; 但是当添加body参数时; 将提示以下错误:
无法加载https://clk528.com/api/article :对预检请求的响应未通过访问控制检查:'Access-Control-Allow-Origin'标头包含多个值'*, http://127.0。 0.1:8100 ',但只允许一个。 因此,不允许访问来源' http://127.0.0.1:8100 '。
我的http服务代码:
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs";
import {tap, catchError} from "rxjs/operators";
import {of} from "rxjs/observable/of";
import {Events} from "ionic-angular";
@Injectable()
export class HttpService {
constructor(public http: HttpClient, private event: Events) {
}
public get<T>(url: string): Observable<T> {
let headers = new HttpHeaders();
return this.http.get<T>(url, {headers: headers}).pipe(
tap(model => console.log(model)),
catchError(this.handleError<T>(url))
);
}
public post<T>(url: string, body: any = null): Observable<T> {
let headers = new HttpHeaders();
return this.http.post<T>(url, body, {
headers: headers
}).pipe(
tap(model => console.log(model)),
catchError(this.handleError<T>(url))
);
}
private handleError<T>(operation = "operation", result?: T) {
return (error: any): Observable<T> => {
if (error.status) {
switch (error.status) {
case 401:
this.event.publish("user::unautherized");
break;
default:
break;
}
}
// TODO: send the error to remote logging infrastructure
console.error(error, operation, result); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
如果我使用以下代码进行请求,则没有错误; 并且可以做到; 我的服务器也将返回数据。
this.http.post('https://clk528.com/api/article')
但是,当我添加参数时,它将描述上面生成的错误。
this.http.post('https://clk528.com/api/article', {
page: 1
});
这是CORS错误。 我不确定为什么在发布请求中传递正文会导致此错误。 您的错误表明允许多个来源访问服务器,但服务器仅允许一个来源访问它,按来源,我是指某种方式的设备。 您可以尝试的一种解决方案是从服务器上允许的来源列表中删除“ http://127.0.0.1:8100 ”,而仅允许“ *”作为允许的来源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.