我使用 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 许可协议
你一半 1⁄2 这里的解决方案。
您缺少的是一个 OPTIONS 路由,其中还需要添加这些标头。