我正在尝试从 ionic android 应用程序中的实时服务器获取 API 数据,但它返回此错误:
Access to XMLHttpRequest at 'https://example.com/api/categories/' from origin 'http://192.168.43.71:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
现在我将 Laravel 用于实时服务器,这里提供的 API 是我在 Laravel 应用程序中设置 CORS 的方式:
/bootstrap/app.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: *');
// rest of the file
由于我上面的设置,我在 CORS 测试仪上得到了这个结果
所以我一直在阅读如何解决这个问题,并遇到了许多类似的解决方案,这就是我添加到我的ionic.config.json
文件中的内容
"proxies": [
{
"path": "/api/*",
"proxyUrl": "https://example.com/api/"
}
]
这是我如何请求我的 get 方法
apiUrl = 'https://example.com/api/categories/';
constructor(private http: HttpClient) { }
getCategories(): Observable<any> {
return this.http.get(`${this.apiUrl}`).pipe(
map(categories => categories)
);
}
知道我还应该做些什么来解决这个问题吗?
感谢您Stephen Romero
指出此解决方案的重要部分,
根据 stephen 的回答,我将此代码添加到我的函数中:
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
并在我的 get 请求中使用它,例如:
return this.http.get(`${this.apiUrl}`, httpOptions).pipe(
现在,我在我的 Laravel 应用程序上使用(安装)了这个包,并将配置文件设置为以下代码:
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['GET', 'OPTIONS'],
'exposedHeaders' => [],
'maxAge' => 0,
];
像这样设置你的标题:
if($request_method = 'GET'){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Expires, Pragma, DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range');
header("Access-Control-Expose-Headers: *");
}
这个头文件最重要的部分是Access-Control-Allow-Headers
部分,如果你只是使用*
它是行不通的!您需要设置标题名称。
希望能帮助到你。
忘记提及为了避免错误,301
您需要/
从 api url 的末尾删除。
// my api (before)
https://example.com/api/categories/
//changed to
https://example.com/api/categories
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句