dshyu6866 2017-07-27 08: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 09: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部