dshyu6866 2017-07-27 16:41
浏览 83
已采纳

对symfony api的ajax请求返回没有'Access-Control-Allow-Origin'标头存在

I am making simple application with React that sends ajax requests to API made with Symfony. I am developing both the react app and symfony api. I am sending request from localhost:3000 to localhost:8000. Here is the ajax request that I am sending

addUser (data) {
    console.log('made it')
    let request = {
      method: 'post',
      url: 'http://127.0.0.1:8000/user/post',
      data: JSON.stringify({'username': data}),
      contentType: 'application/json'
    }
    $.ajax(request)
      .done(data => this.addUserSuccess(data))
      .fail(err => this.addUserFail(err))
  }

and here is the Symmfony app that takes care of the request

/**
     * Creates a new user entity.
     *
     * @Route("/post", name="user_new")
     * @Method({"GET", "POST"})
     */
    function newAction(Request $request ) {
        echo $request;
        $body = $request->getContent();
        $body = json_decode($body,true);
        $username = $body['username'];
        $user = new User($username);
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        return new JsonResponse($user,200,array('Access-Control-Allow-Origin'=> '*'));
    } 

I am so far in the beginning and as you can see I am creating new user without password, security or anything. I just want to make it work and be able to send request from the app to the api. Here is the result

XMLHttpRequest cannot load http://127.0.0.1:8000/user/post. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405.

I have seen many questions like this one before and one of the answers was to return JsonResponse with the header and as you can see it does not work.

Here is one of the quenstions whose answer I followed - Origin is not allowed by Access-Control-Allow-Origin but unfortunately with no success.

Can you tell me how to fix it? Thank you in advance!

  • 写回答

2条回答 默认 最新

  • doumeng1089 2017-07-27 17:00
    关注

    Here's what I'm doing for the same situation. In app/config/config_dev.yml, add a new service. Putting this in config_dev.yml means this will only affect requests through app_dev.php.

    services:
        app.cors_listener:
            class: AppBundle\Security\CorsListener
            tags:
                - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
    

    And the contents of AppBundle/Security/CorsListener.php:

    <?php
    namespace AppBundle\Security;
    
    use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
    
    // Based on http://stackoverflow.com/a/21720357
    class CorsListener
    {
        public function onKernelResponse(FilterResponseEvent $event)
        {   
            $responseHeaders = $event->getResponse()->headers;
    
            $responseHeaders->set('Access-Control-Allow-Headers', 'origin, content-type, accept, credentials');
            $responseHeaders->set('Access-Control-Allow-Origin', 'http://localhost:8080');
            $responseHeaders->set('Access-Control-Allow-Credentials', 'true');
            $responseHeaders->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 带序列特征的多输出预测模型
  • ¥15 VB.NET读取电脑主板序列号
  • ¥15 Python 如何安装 distutils模块
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?
  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错