请求标题字段Access-Control-Allow-Origin在使用angular 5的预检响应中不允许使用Access-Control-Allow-Origin

时间:2018-05-16 14:41:05

标签: angular5

service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

const httpOptions = {
    // headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8080', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers':'X-Requested-With' }),
    headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:4200', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Credentials':'true','Access-Control-Allow-Headers':'X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization','Access-Control-Expose-Headers':'xsrf-token' }),
    params: new HttpParams({})
};


@Injectable()
export class DemoService {

    constructor(public http: HttpClient) { }

    postData(doctor) {
        let new_doctor = JSON.stringify(doctor);
        return this.http.post('http://a.com/api/doctors/doctor', new_doctor, httpOptions);
    }

    get_doctor_list() {
        return this.http.get('http://a.com/api/doctors/doctor');
    }

    update_doctor_details(data,id) {
        let details = JSON.stringify(data);
        return this.http.put('http://a.com/api/doctors/doctor/id/' + id, details, httpOptions);
    }
}


component

    onSubmit(createdoctor:NgForm) {
        this.doctor_details = createdoctor.value;
        this.notvalid = createdoctor.valid == true?false:true;
        let date = new Date();
        let created_date = this.datePipe.transform(date, 'yyyy-MM-dd');
        this.doctor_details.Id = this.maxid;
        this.doctor_details.create_date = created_date;
        this.doctor_details.status = "1";
        this._demoService.postData(this.doctor_details).subscribe(
            error => {
                console.error("Error saving data!");
            }
        );
    }

但是我得到了error

  

请求标题字段Access-Control-Allow-Origin在预检响应中不允许使用Access-Control-Allow-Origin。

我是角色5的初学者。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

CORS标头,以Access-Control-开头的标头是响应标头,它们必须由服务器设置并从服务器发送到浏览器,而不是相反,这就是你的错误

答案 1 :(得分:0)

我有同样的问题。

违反的原因是在Angular应用程序配置中有一个HttpInterceptor

    const secureReq = req.clone({ body: newBody });
    return next.handle(secureReq);

即使这段代码并没有真正做任何事情,它也会导致无关的标头出现在前往外部服务的HTTP GET请求中并触发了HTTP OPTIONS请求。只要确保您的接收器不会与外部资源混淆:

    if(!req.url.startsWith("https://myapiservice.io")) {
      return next.handle(req);
    }

答案 2 :(得分:-1)

尝试使用 Safari浏览器禁用CORS限制。 如果有效,那么您必须对浏览器做些事情。

只需单击

Develop > Disable Cross-Origin Restrictions

在菜单栏中。

为了获得“开发”菜单,请执行以下操作:

Preferences > Advanced > Show Develop menu in menu bar.
  

如果您不想更改浏览器设置,那么唯一的方法是   通过在服务器上通过代理执行此请求来实现   一侧。