不允许 CORS 来源请求
CORS Origin Request not allowed
我有一个用 Slim Framework 编写的 API。 API 给了我所有正确的 json 响应,但我正在努力发出 ajax 请求,因为浏览器阻止我的请求说 没有 'Access-Control-Allow-Origin' header 出现在请求的资源 上。我写了一个基于 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);
}
}
即使我设置了 response->withHeader('Access-Control-Allow-Origin', '*') 我也没有得到 header回复 所以问题依旧。
浏览器通过 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);
});
我有一个用 Slim Framework 编写的 API。 API 给了我所有正确的 json 响应,但我正在努力发出 ajax 请求,因为浏览器阻止我的请求说 没有 'Access-Control-Allow-Origin' header 出现在请求的资源 上。我写了一个基于 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);
}
}
即使我设置了 response->withHeader('Access-Control-Allow-Origin', '*') 我也没有得到 header回复 所以问题依旧。
浏览器通过 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);
});