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!