douxian1923
2019-07-12 17:22 阅读 277

跨源请求已阻止:同源策略禁止读取远程资源不起作用

I'm new to Laravel and have gone through several solutions on tackoverflow, but to no avail. It's still showing the same error of Cross-Origin Request Blocked.

$(".cmd_submit").click(function(){
$.ajax({
    //crossOrigin: true,
    //header:{'Access-Control-Allow-Origin': '*'},
    type: 'POST',
    url:  'http://localhost/members/register',
    data: $('#form_reg').serialize(),
    success: function(data){
       alert(data);
    },
    error: function(data){
  alert(data);
    }

I also included this:

<?php header("Access-Control-Allow-Origin: *"); ?>

on my app.blade.php, but it still didn't work.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • duanjuelian4640 duanjuelian4640 2019-07-12 18:05

    You need to set config/cors.php content.

    Mine looks like this:

    return [
    
        /*
        |--------------------------------------------------------------------------
        | Laravel CORS
        |--------------------------------------------------------------------------
        |
        | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
        | to accept any value.
        |
        */
    
        'supportsCredentials' => false,
        'allowedOrigins' => ['*'],
        'allowedHeaders' => ['*'],
        'allowedMethods' => ['*'],
        'exposedHeaders' => [],
        'maxAge' => 0,
    
    ];
    

    UPDATE:

    I'm sorry I was not very clear here. You need to install barryvdh/laravel-cors library first and it will allow OPTIONS request to get 200 response with needed headers. Laravel does not come with this package so Chrome (or any other modern browser) will see that Cross-Origin headers are missing and will block the request.

    点赞 评论 复制链接分享

相关推荐