【问题标题】:CORS - Lumen and Angular requestCORS - 流明和角度请求
【发布时间】:2018-05-12 14:30:27
【问题描述】:

我有一个在 http://localhost:4200 运行的 Angular 应用程序和一个在 http://localhost:8000 运行的 Lumen API。

我正在使用 barryvdh/laravel-cors,我的所有 POSTS 请求都返回“请求的资源上没有 'Access-Control-Allow-Origin' 标头。”

有什么线索吗?我的 Angular 数据库服务:

@Injectable()
export class DatabaseService {

  constructor(private http: Http) { }

  get(url: string) {
    return this.http.get("http://localhost:8000/" + url)
      .map(response => response.json());
  }

  post(url: string, data) {
    return this.http.post("http://localhost:8000/"+ url, data)
      .map(response => response.json());
  }

}

所有 GET 请求都能正常工作。

【问题讨论】:

  • 你解决了这个问题吗?因为我遇到了同样的问题。
  • @Shivam 在 localhost 我刚刚使用了一个名为 CORS 的 Chrome 扩展程序,它解决了这个问题。

标签: angular cors lumen


【解决方案1】:

这取决于您传递的数据以及您在后端的处理方式。你有没有尝试对数据进行字符串化

JSON.stringify(data)

post(url: string, data) {
return this.http.post("http://localhost:8000/"+ url, JSON.stringify(data))
  .map(response => response.json());
}

【讨论】:

    【解决方案2】:

    您需要在 Lumen 上授予对 Angular 服务器的访问权限

    如果你没有使用 CORS,只需在 /bootstrap/app.php 中添加这一行

    header('Access-Control-Allow-Origin: http://localhost:4200/');
    

    或所有人:

    header('Access-Control-Allow-Origin: *');
    

    如果您使用 CORS,则必须在 App\Http\Middleware\CorsMiddleware(或任何称为 CORS 文件的文件)的标题上设置相同的内容

    $headers = [
                'Access-Control-Allow-Origin'      => '*',
                'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Max-Age'           => '86400',
                'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
            ];
    

    【讨论】:

    • 我正在尝试这个,但它不起作用..我已经测试过是否正在调用中间件(正在调用die()).. GET 请求很好,但 POST/PUT只是似乎摔倒了。 $headers = [ 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE', 'Access-Control-Allow-Credentials' => 'true', 'Access-Control-Max-Age' => '86400', 'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With' ];
    • 忽略我... Angular 应用程序中的 URL 错误。设置为转到 GET URL.. face palm
    【解决方案3】:

    启用 apache mod_headers 将解决此问题。 运行以下命令

    1. a2enmod 标头
    2. sudo service apache2 重启

    【讨论】:

      猜你喜欢
      • 2019-07-17
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 2021-12-13
      • 2021-06-08
      相关资源
      最近更新 更多