【问题标题】:CORS Origin Request not allowed不允许 CORS 源请求
【发布时间】:2018-07-28 07:16:13
【问题描述】:

我有一个用 Slim 框架编写的 API。 API 为我提供了所有正确的 json 响应,但我正在努力发出 ajax 请求,因为浏览器阻止了我的请求,说 请求的资源上不存在“Access-Control-Allow-Origin”标头。我已经根据 Slim 的默认值编写了一个响应方法,它看起来像这样:

public function withCustomJson($meta = null, $data = null)
    {
        if (isset($data)) {
            $finalResponse['data'] = $data;
        }

        $finalResponse['meta'] = array(
            'status' => (isset($meta['status']) ? $meta['status'] : null),
            //'message' => (isset($meta['message']) ? $meta['message'] : null),
            'message' => (isset($meta['message']) ? mb_convert_encoding($meta['message'], "UTF-8", "auto") : null),
            //'responseStatus' => (isset(self::$messages[$statusData['codStatus']]) ? self::$messages[$statusData['codStatus']] : null)
        );

        $response = $this->withBody(new Body(fopen('php://temp', 'r+')));
        $response->body->write($json = json_encode($finalResponse));

        // Ensure that the json encoding passed successfully
        if ($json === false) {
            throw new \RuntimeException(json_last_error_msg(), json_last_error());
        }

        $responseWithJson = $response->withHeader('Content-Type', 'application/json;charset=utf-8')
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization');
        if (isset($meta['codStatus'])) {
            return $responseWithJson->withStatus($meta['codStatus']);
        }
        return $responseWithJson;
    }

这是我的 ajax 请求的基本功能:

function ajaxRequest(verb, endpoint, headers = null, body = null, async = true) {
    try {
        //Animação do loading
        $('body').waitMe({
            effect: 'facebook',
            text: 'Carregando...',
            waitTime: 8000
        });

        return $.ajax({
            ContentType: 'application/json',
            url: 'http://api.mydonmain.com.br/' + endpoint,
            type: verb,
            async: async,
            headers: {
                'xAuthChaveApi': localStorage.xAuthChaveApi,
                'xAuthCambistaID': cambistaLocal !== null ? cambistaLocal.id : null,
                'xAuthCambistaToken': cambistaLocal !== null ? cambistaLocal.sessao[0].token : null
            },
            data: body,
            error: function (error) {
                notificar(Status.SERVER_ERR);
            },
            beforeSend: function (xhr) {
                if (headers !== null) {
                    for (var key in headers) {
                        xhr.setRequestHeader(key, headers[key]);
                    }
                }
            },
            // complete: function() {
            //     $('#content').waitMe('hide');
            // }
        });
    } catch (error) {
        notificar(error);
    }

}

即使我设置了 response->withHeader('Access-Control-Allow-Origin', '*') 我没有得到响应的标题,因此问题仍然存在.

【问题讨论】:

  • 对于初学者来说,您在 AJAX 请求中发送的标头比Access-Control-Allow-Headers 允许的更多/不同。如果还不是这样,那么您可能没有正确处理预检请求。
  • 我已经删除了允许的标头 especification,但它并没有解决我的问题。我很抱歉我的无知,但是如何正确处理预检?

标签: ajax rest api cors slim


【解决方案1】:

浏览器通过OPTIONS http 方法启动 CORS 预检检查。 尝试添加此中间件并给我反馈。

// CORS preflight middleware
$app->add(function (Request $request, Response $response, $next) {
    if ($request->getMethod() !== 'OPTIONS' || php_sapi_name() === 'cli') {
        return $next($request, $response);
    }
    $response = $response->withHeader('Access-Control-Allow-Origin', '*');
    $response = $response->withHeader('Access-Control-Allow-Methods', $request->getHeaderLine('Access-Control-Request-Method'));
    $response = $response->withHeader('Access-Control-Allow-Headers', $request->getHeaderLine('Access-Control-Request-Headers'));
    return $next($request, $response);
});

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2020-12-29
    • 2015-03-09
    • 2016-09-15
    • 2019-07-02
    • 2016-11-18
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多