我尝试在我自己主要用于 AJAX 的路由上执行 file_get_contents()
:
file_get_contents($this->router->generate('ajax_get_provinces', array('country' => $country->getName()), true));
我得到一个错误:
Warning: file_get_contents(http://symfony.trainingexperience.org/ajax/get-provinces/Spain): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
行动:
/**
* GET method
*
* @Route("/ajax/get-provinces/{country}", name="ajax_get_provinces")
*
* @param $country
* @param Request $request
*
* @return JsonResponse
*/
public function getProvinces($country, Request $request)
{
$translator = $this->get('translator');
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => $translator->trans('ajax.access.error')), 400);
}
...
return new JsonResponse($provinces, 200);
}
最佳答案
这是你的问题,我会说:
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => $translator->trans('ajax.access.error')), 400);
}
file_get_contents 没有为被识别为 XmlHttpRequest (X-Requested-With) 的请求设置所需的 header
/**
* Returns true if the request is a XMLHttpRequest.
*
* It works if your JavaScript library sets an X-Requested-With HTTP header.
* It is known to work with common JavaScript frameworks:
*
* @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
*
* @return bool true if the request is an XMLHttpRequest, false otherwise
*/
public function isXmlHttpRequest()
{
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}
尝试使用正确的 header 通过 curl 执行您的请求,或者在您的操作中删除 XMLHttpRequest 检查。
在这里您可以阅读如何通过 curl 发出请求: PHP: Simulate XHR using cURL
编辑: 要使用 file_get_contents 设置所需的 header ,您可以试试这个
$options = array(
'http' => array(
'header' => "Accept:application/json\r\n" .
"X-Requested-With:XMLHttpRequest\r\n",
'method' => 'GET'
),
);
$context = stream_context_create($options);
file_get_contents($this->router->generate('ajax_get_provinces', array('country' => $country->getName()), true, $context));
如果没有其他 header 丢失,这可能会起作用。
关于php - Symfony2 - file_get_contents() 在同一项目 api url 上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43680140/