0

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!

Pavlin Petkov
  • 1,022
  • 3
  • 17
  • 38
  • I looked through some of your questions, and noticed a few with answers that might be appropriate to accept, [including your own answers](https://stackoverflow.blog/2009/01/06/accept-your-own-answers/). This is just a friendly reminder to [accept answers](https://stackoverflow.com/help/someone-answers) if your problem has been solved :) – aplum Jul 28 '17 at 14:26

2 Answers2

2

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');
    }
}
aplum
  • 188
  • 1
  • 8
  • Thank you, this worked! I must add that in my function I had to add OPTIONS as the allowed methods. For some reason the Symfony api accepts the request but has internal server error. Can you tell me how could I debug an api? Meaning how can I put information on the console and view what actually happens?? Something like dump() that would work on the console – Pavlin Petkov Jul 28 '17 at 06:25
  • I'm only just learning symfony myself, and it's been a while since I've used it, so maybe someone else could help more with that. But to start, check [this answer](https://stackoverflow.com/a/2687747) and your server's error logs to help with that internal server error. – aplum Jul 28 '17 at 13:53
1

You need to set the correct headers on your PHP file.

 header('Access-Control-Allow-Origin: *');
Vipul Solanki
  • 313
  • 1
  • 2
  • 19
luispa
  • 133
  • 3
  • 7
  • Just to give more context https://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control-allow-origin – Devesh Jul 27 '17 at 16:46
  • 1
    In which php file? I added the code on the beginning of the function and it still does not work. I am using Symfony and it has lots of files and I have no idea where should I put this. In the AppKernel? app.php? I thought it has to be in the response and this is why in the JsonResponse as last parameter I send array with headers and in this case the header is `Access-Control-Allow-Origin` with value `*`. Still nothing – Pavlin Petkov Jul 27 '17 at 16:49