【发布时间】: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,但它并没有解决我的问题。我很抱歉我的无知,但是如何正确处理预检?