【问题标题】:Cors header error with ajax request requestajax请求请求的Cors标头错误
【发布时间】:2021-11-02 19:54:37
【问题描述】:

我正在尝试向 musicbrainz api 发出 ajax 请求,但不断收到 cors 标头错误。

错误:Access to XMLHttpRequest at 'https://musicbrainz.org/ws/2/release-group/?xxxxxxx' from origin 'https://my_url' has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

代码

var $artist_encoded = encodeURIComponent($artist);
var $album_encoded = encodeURIComponent($album);

$.ajax({
    type: "GET",
    url: "https://musicbrainz.org/ws/2/release-group/?query=artist:%22" + $artist_encoded + "%22%20AND%20releasegroup:%22" + $album_encoded + "%22",
    dataType: "xml",
    success: myfunction
});

【问题讨论】:

    标签: javascript jquery laravel csrf


    【解决方案1】:

    // i hope it help you 
    $.ajax({
      url: "https://musicbrainz.org/ws/2/place/478558f9-a951-4067-ad91-e83f6ba63e74?inc=aliases",
        headers: {
                'Content-Type':'text/xml',
            }, 
      dataType: "text",
      success: function(text) {
     console.log(text)
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    【讨论】:

      【解决方案2】:

      跨域资源共享 (CORS) 是一种基于 HTTP 标头的机制,它允许服务器指示浏览器应允许从其加载资源的任何来源(域、方案或端口),而不是它自己的来源。因此,您必须向客户端(ajax 请求)添加权限才能接收来自服务器端的响应。

      您可以通过创建新的中间件来解决此问题:

      <?php
      
      namespace App\Http\Middleware;
      
      use Closure;
      
      class Cors
      {
          /**
           * Handle an incoming request.
           *
           * @param  \Illuminate\Http\Request  $request
           * @param  \Closure  $next
           * @return mixed
           */
          // Cors middleware for allow api access from client side 'vue project' 
          public function handle($request, Closure $next)
          {
              return $next($request)
                  ->header('Access-Control-Allow-Origin','*')
                  ->header('Access-Control-Allow-Methods','*')
                  ->header('Access-Control-Allow-Headers','*')
              ;
          }
      }
      

      在kernel.php注册新的中间件: 在中间件数组中添加:

      protected $middleware = [
              \App\Http\Middleware\Cors::class,
          ];
      

      在路由中间件数组中添加:

      protected $routeMiddleware = ['cors' => \App\Http\Middleware\Cors::class,
          ];
      

      最后将这个中间件实现到路由中:

      Route::group(['middleware' => ['cors']], function () {
      //... your routes
      });
      

      结果添加时: -&gt;header('Access-Control-Allow-Origin','*') 这意味着您允许任何其他来源访问您的应用程序。您可以只添加要访问您的应用程序的特定路由数组。在你的情况下,我认为是['127.0.0.1:8000']

      【讨论】:

        猜你喜欢
        • 2013-01-29
        • 2014-05-26
        • 2023-03-21
        • 2016-08-27
        • 2020-05-06
        • 2017-04-21
        • 1970-01-01
        • 2015-03-01
        • 2015-12-15
        相关资源
        最近更新 更多