Laravel 和 angularjs 得到 405 Method not allowed 错误

Posted

技术标签:

【中文标题】Laravel 和 angularjs 得到 405 Method not allowed 错误【英文标题】:Laravel and angularjs getting 405 Method not allowed error 【发布时间】:2015-07-10 22:22:32 【问题描述】:

我已经安装了 laravel homestead,它工作正常我能够与后端通信并使用 API 获得响应。现在我还安装了 angularjs,它似乎也可以工作,但不起作用的是从 Angular 应用程序作为前端 POST 或 GET 到 laravel API。我在 Firefox 检查器网络中收到以下错误:

405 Method Not Allowed
request headers 
Host: demo.app:8000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Gecko/20100101 Firefox/37.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://frontend.app:8000
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Response Header
Cache-Control: no-cache
Connection: keep-alive
Content-Type: text/html; charset=UTF-8
Date: Fri, 01 May 2015 02:28:25 GMT
Server: nginx/1.6.2
Set-Cookie: laravel_session=
Transfer-Encoding: chunked

在控制台日志中:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://demo.app:8000/myUrl This can be fixed by moving the resource to the same domain or enabling CORS.

我不太确定他们为什么不沟通我正确地遵循了所有的说明,而且他们独立工作正常(Laravel API 和 Angularjs 用于前端)。任何想法和帮助将不胜感激

【问题讨论】:

【参考方案1】:

您需要在 /app/filters.php 中添加/替换这些行

App::before(function ($request) 
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
);

【讨论】:

DevManny,这是一个已经有很多文件的大项目;我最近刚刚更改了环境,将其移至另一个网络,当问题发生时,但当我在旧网络上时,一切正常。我不知道您是要我在这里发布整个项目还是只发布相关代码。但无论如何,我包含了一些我认为相关的代码作为答案: 我没有在 laravel 5.6 中看到 filters.php 文件

以上是关于Laravel 和 angularjs 得到 405 Method not allowed 错误的主要内容,如果未能解决你的问题,请参考以下文章

在 Laravel&Angular 项目中分离 AngularJS 控制器文件

结合 AngularJS 和 Laravel 路由

同时使用 Laravel 和 Angularjs 路由

Laravel 4 和 AngularJS - 使用路由清理 URL

AngularJS 和 Laravel - CORS

使用 IIS、AngularJS 和 Laravel 删除 MethodNotAllowedHttpException