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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵