CORS 发布请求失败

新手上路,请多包涵

我使用 SLIM 微框架构建了一个 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 请求工作得很好。

原文由 Jerome Carter 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 315
2 个回答

你一半 12 这里的解决方案。

您缺少的是一个 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');
});

原文由 geggleto 发布,翻译遵循 CC BY-SA 3.0 许可协议

CORS 可能很难配置。关键是您需要在服务器和客户端中设置特殊标头,据我所知,我没有看到任何 Vue 标头设置 http 不是函数。但是,这里有一些用于发布请求的设置。

 const data = {
    email: email,
    password: password
  }
const options = {
    headers: {
        'Access-Control-Expose-Headers': // all of your headers,
        'Access-Control-Allow-Origin': '*'
    }
}
Vue.http.post('api/auth/register', JSON.stringify(data), options).then(response => {
    // success
}, response => {
    // error
})

请注意,您需要对数据进行字符串化,并且需要公开标头,通常包括 Access-Control-Allow-Origin 标头。我在自己的一个应用程序中所做的是定义拦截器,因此我不必担心为每个请求设置标头。

 Vue.http.headers.common['Access-Control-Expose-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, x-session-token, timeout, Content-Length, location, *'
Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'

原文由 Yerko Palma 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏