[英]web api 2 CORS No 'Access-Control-Allow-Origin' header is present
[英]Ionic app CORS No 'Access-Control-Allow-Origin' header is present, using Lumen API with CORS middleware
我正在构建一个使用流明API的应用程序。 在流明项目中,我在互联网上找到了两个文件,同时查找如何在流明中处理CORS。
CorsMiddleware.php:
<?php
namespace App\Http\Middleware;
class CorsMiddleware {
public function handle($request, \Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');
return $response;
}
}
CatchAllOptionsRequestsProvider.php:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
/**
* If the incoming request is an OPTIONS request
* we will register a handler for the requested route
*/
class CatchAllOptionsRequestsProvider extends ServiceProvider {
public function register()
{
$request = app('request');
if ($request->isMethod('OPTIONS'))
{
app()->options($request->path(), function() { return response('', 200); });
}
}
}
这两个文件修复了我最初的CORS问题。 我能够执行GET并从API接收数据。 但是,当我尝试对API进行POST方法时,我再次收到以下错误:“所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,源' http:// localhost:8100 '并不存在允许访问。”
检查chrome中的网络标签后,有两个请求。 第一个是OPTIONS请求,我认为这只是从服务器获取允许的标头。 第二个请求是我的POST请求,带有正确的有效负载。 它们都返回200 OK的状态代码,但是我仍然收到上面提到的Access-Control错误。
使用POSTMAN将数据发送到我的API时可以使用,但是当我在浏览器中使用Ionic Serve时不能使用
对于那些想知道的人,我使用Ionic的$ http方法进行调用:
MORE CODE.......
var req = {
method: 'POST',
url: APIUrl + 'register',
timeout: timeout.promise,
data: {"name": "Michael"}
}
$http(req).then(function(res) {
.......MORE CODE
可能与服务器apache配置有关吗? 我启用了mod_rewrite。 任何帮助,将不胜感激。 谢谢
如果您控制服务器,则可能需要在其中设置所需的标头。 根据哪个服务器,这可能会有所帮助: http : //enable-cors.org/server.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.