Jer*_*ter 5 javascript slim cors vue.js vue-resource
我使用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');
}
}
Run Code Online (Sandbox Code Playgroud)
对于我的前端,我使用了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
})
}
Run Code Online (Sandbox Code Playgroud)
在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.
Run Code Online (Sandbox Code Playgroud)
奇怪的是,GET请求可以完美地工作。
你把这里的解决方案减半1/2。
您缺少的是 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');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5601 次 |
| 最近记录: |