laravel 飞行响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Content-Type

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49333264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:31:30  来源:igfitidea点击:

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in flight response

phpangularlaravellaravel-5cors

提问by Sam

I am developing an Angular 4 application with Laravel (Restful API). I have tested the API with Postman. It's working fine but when I call the API from Angular 4 I am getting this error:

我正在使用 Laravel(Restful API)开发 Angular 4 应用程序。我已经用 Postman 测试了 API。它工作正常,但是当我从 Angular 4 调用 API 时,我收到此错误:

enter image description here

在此处输入图片说明

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { User } from '../models/user';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AuthService {
 private BASE_URL: string = 'http://localhost/fmfb_hr/public/api';
  private headers: Headers = new Headers({'Content-Type': 'application/json'});
 constructor(private http: Http) {}
login(user): Promise<any> {
let url: string = `${this.BASE_URL}/login`;
return this.http.post(url, user, {headers: this.headers}).toPromise();
}


}

回答by Meysam Mahmoodi

Add these three lines to CORSify your server. If you used Apache as web server, add these lines to your .htaccessfile:

将这三行添加到 CORSify 您的服务器。如果您使用 Apache 作为 Web 服务器,请将这些行添加到您的.htaccess文件中:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET,PUT,POST,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"

回答by Sheraz Khan

Try this code add both header in one request, I hope this works

试试这个代码在一个请求中添加两个标头,我希望这有效

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { User } from '../models/user';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AuthService {
    private BASE_URL: string = 'http://localhost/fmfb_hr/public/api';
    private headers: Headers = new Headers({});
    constructor(private http: Http) {}
    login(user): Promise<any> {
        let url: string = `${this.BASE_URL}/login`;
        this.headers.append('Content-Type','application/x-www-form-urlencoded');
        this.headers.append('Content-Type','application/json');
        return this.http.post(url, user, {headers: this.headers}).toPromise();
    }
}