gpt4 book ai didi

javascript - ionic 应用程序 CORS 不存在 'Access-Control-Allow-Origin' header ,使用带有 CORS 中间件的 Lumen API

转载 作者:行者123 更新时间:2023-11-30 15:41:05 35 4
gpt4 key购买 nike

我正在构建一个使用 Lumen API 的应用程序。在 Lumen 项目中,我在查找如何在 Lumen 中处理 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’ header 。因此不允许访问 Origin‘http://localhost:8100’。”

检查 chrome 中的网络选项卡后,有两个请求。第一个是 OPTIONS 请求,我认为这只是为了从服务器获取允许的 header 。第二个请求是我的带有正确负载的 POST 请求。它们都返回 200 OK 的状态代码,但我仍然收到上述访问控制错误。

在使用 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。对此的任何帮助将不胜感激。谢谢

最佳答案

如果您控制着服务器,您可能需要在那里设置所需的 header 。根据哪个服务器,这可能会有所帮助: http://enable-cors.org/server.html

关于javascript - ionic 应用程序 CORS 不存在 'Access-Control-Allow-Origin' header ,使用带有 CORS 中间件的 Lumen API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40806045/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com