php - Symfony2 - file_get_contents() 在同一项目 api url 上失败

标签 php symfony http request

我尝试在我自己主要用于 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/

相关文章:

api - 保护使用 Play Framework 开发的 REST API

php - count(array)返回1,但数组为空

php - 尝试从命名空间加载类时是否忘记了另一个命名空间的 "use"语句?

php - 不能使用 Symfony\Component\HttpFoundation\File\UploadedFile 类型的对象作为数组 Laravel 4.2 文件上传

javascript - Ajax 操作真的应该有单独的 URL 吗?

facebook - 对几乎相同的 URL(HTTP、HTTPS)的计数

php - 运行 wood-starter-theme 时未找到类 'Timber'

php - Laravel sortBy() 在输出中包含键,但 sortByDesc 没有?

javascript - 更改选择框上 ajax 的状态

symfony - 在 Doctrine EventListener 中获取用户