javascript – CORS发布请求失败

我使用SLIM Micro-Framework构建了一个API.我设置了一些使用以下代码添加CORS头的中间件.

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

}

对于我的前端,我使用了VueJS.我设置了VueResource并使用以下代码创建了一个函数.

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
})
}

在chrome中,将以下错误记录到控制台.

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.

奇怪的是,GET请求完美无缺.

解决方法:

你在这里解决方案的一半.

您缺少的是OPTIONS路线,其中还需要添加这些标题.

$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');
});
上一篇:php – 如何修改路由执行前后的slim v3响应体?


下一篇:php – Slim 3 – 斜线作为路由参数的一部分