CORS Post Request Fails CORS Post Request Fails vue.js vue.js

CORS Post Request Fails


You half 1/2 the solution here.

What you are missing is an OPTIONS route where these headers need to be added as well.

$app->options('/{routes:.+}', function ($request, $response, $args) {    return $response        ->withHeader('Access-Control-Allow-Origin', 'http://mysite')        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');});


This happens because preflight request is of OPTIONS type. You need to make an event listener on your request, which checks the type and sends a response with needed headers.

Unfortunately i don't know Slim framework, but here's the working example in Symfony.

First the headers example to be returned:

// Headers allowed to be returned.const ALLOWED_HEADERS = ['Authorization', 'Origin', 'Content-Type', 'Content-Length', 'Accept'];

And in the request listener, there's a onKernelRequest method that watches all requests that are coming in:

    /**     * @param GetResponseEvent $event     */    public function onKernelRequest(GetResponseEvent $event)    {        // Don't do anything if it's not the master request        if (!$event->isMasterRequest()) {            return;        }        // Catch all pre-request events        if ($event->getRequest()->isMethod('OPTIONS')) {            $router = $this->container->get('router');            $pathInfo = $event->getRequest()->getPathInfo();            $response = new Response();            $response->headers->set('Access-Control-Allow-Origin', $event->getRequest()->headers->get('Origin'));            $response->headers->set('Access-Control-Allow-Methods', $this->getAllowedMethods($router, $pathInfo));            $response->headers->set('Access-Control-Allow-Headers', implode(', ', self::ALLOWED_HEADERS));            $response->headers->set('Access-Control-Expose-Headers', implode(', ', self::ALLOWED_HEADERS));            $response->headers->set('Access-Control-Allow-Credentials', 'true');            $response->headers->set('Access-Control-Max-Age', 60 * 60 * 24);            $response->send();        }    }

Here i just reproduce the Origin (all domains are allowed to request the resource, you should probably change it to your domain).Hope it will give some glues.


Actually CORS is implemented at browser level. and Even with

 return $response            ->withHeader('Access-Control-Allow-Origin', 'http://mysite')            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

chrome and Mozilla will not set headers to allow cross origin. So, you need forcefully disable that..

Read more about disabling CORS

Disable same origin policy in Chrome