【问题标题】:Laravel api CORS error when posting from js从 js 发布时 Laravel api CORS 错误
【发布时间】:2019-10-21 08:24:57
【问题描述】:

我使用 Laravel 创建了一个 API,但在尝试发帖时出现错误。我不知道我是否需要从 javascript 发送 crsf 或者我是否将 cors 中间件弄错了。

当我访问 API 时,我没有任何 cors 问题。

这是我的中间件。它已添加到 kernel.php 文件中。

class Cors{
    public function handle($request, Closure $next) {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*') 
            ->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With, x-xsrf-token, ip');
    }
}

在 javascritp 上,我在标题中添加了这个:'Content-Type': 'application/json'。

这是它给我的错误

从源“http://localhost:4200”访问“http://localhost:8000/api/user/1/videos/1/newComment”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。

非常感谢您的帮助。

【问题讨论】:

  • 尝试在$request对象本身而不是$next上调用header
  • 谢谢。但是,如果我从标头调用 $request,情况会变得更糟。 get 也会报错。

标签: laravel


【解决方案1】:

尝试将其添加到项目根目录中 index.php 的顶部...

    <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2017-06-03
    • 2017-10-20
    • 2018-04-07
    • 2022-01-23
    • 2021-03-02
    • 2018-04-03
    相关资源
    最近更新 更多