我正在使用Ionic 3和一个使用Slim Framework的REST Api,可以完全访问服务器。
每次API调用(GET,POST,PUT和DELETE)尽管如此:
let formData = new FormData();
formData.append("file",image);
return this.httpClient.post("https://myurl.com/api/v1/image,formData)
imageURL是我的服务器API,图像是我从cordova相机插件获得的路径。
这是我的服务器错误:
[Error] Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.
[Error] Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.
[Error] XMLHttpRequest cannot load https://hobbyrea.com/api/v1/user/image due to access control checks.
这就是我的服务器端标题:
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
有人可以告诉我为什么我在这次API调用时遇到错误吗?
编辑:
我从iPhone访问API。
编辑2: 我使用cordova文件传输插件。请记住在PHP设置中升级upload_max_filesize。它会为你省去很多头痛:D
答案 0 :(得分:0)
将客户端的Origin添加到您服务器的允许源头。
Access-Control-Allow-Origin: http://localhost:8080