Search code examples
javascriptcorsslimvue.jsvue-resource

CORS Post Request Fails


I built an API with the SLIM Micro-Framework. I setup some middleware that adds the CORS headers using the following code.

class Cors{

    public function __invoke(Request $request, Response $response, $next){

        $response = $next($request, $response);
        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');
    }

}

For my front-end, I used VueJS. I setup VueResource and created a function with the following code.

register (context, email, password) {
  Vue.http({
    url: 'api/auth/register',
    method: 'POST',
    data: {
    email: email,
    password: password
  }
}).then(response => {
  context.success = true
}, response => {
  context.response = response.data
  context.error = true
})
}

In chrome, the following error is logged to the console.

XMLHttpRequest cannot load http://mysite:9800/api/auth/register. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysite' is therefore not allowed access.

Oddly enough, GET requests work perfectly.


Solution

  • 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');
    });