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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘