douchujian8124 2013-11-22 21:20 采纳率: 100%
浏览 206
已采纳

Laravel 4 API不允许来自外部站点的POST请求

I am attempting to create a User via a POST request to my Laravel 4 API from an external site. I've added the following code to my app/filters.php file:

App::before(function($request)
{
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {

        header('Access-Control-Allow-Origin', 'http://www.myexternalsite.net');
        header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With');
        header('Access-Control-Allow-Credentials', 'true');

        exit;
    }
});

App::after(function($request, $response)
{
    $response->headers->set('Access-Control-Allow-Origin', 'http://www.myexternalsite.net');
    $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    $response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
    $response->headers->set('Access-Control-Allow-Credentials', 'true');
    $response->headers->set('Access-Control-Max-Age','86400');
    return $response;
});

when I run my dev tools on the POST request from http://www.myexternalsite.net I get the following warning message:

event.returnValue is deprecated. Please use the standard event.preventDefault() instead. main-built.js:6

and the following error messages:

OPTIONS http://api.mywebsite.com/users 500 (Internal Server Error) main-built.js:7
OPTIONS http://api.mywebsite.com/users No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.myexternalsite.net' is therefore not allowed access. main-built.js:7

Am I missing something?

  • 写回答

1条回答 默认 最新

  • dousuo8400 2013-11-22 21:30
    关注

    The first error is strictly a client-side javascript error. The error description means exactly what it says. You should update your js appropriately.

    The second set of error message probably related to the fact you are making a cross-domain request for a javascript file which is not subject to your headers being sent by PHP. You would need to configure CORS on webserver for such endpoint

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line