我有一个用Slim Framework编写的API。 API给了我所有正确的json响应,但我正在努力制作ajax请求,因为浏览器阻止我的请求说没有'Access-Control-Allow-Origin'标头出现在请求的资源上。我写了一个基于Slim默认的respone方法,它看起来像这样:
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);
}
}
即使我正在设置响应 - > withHeader('Access-Control-Allow-Origin','*')我没有得到响应上的标题因此问题仍然存在。
答案 0 :(得分:0)
浏览器通过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);
});