SOLVED
谢谢Stephen Romero
为了指出这个解决方案的重要部分,
根据斯蒂芬的回答,我将此代码添加到我的函数中:
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
并在我的 get 请求中使用它,例如:
return this.http.get(`${this.apiUrl}`, httpOptions).pipe(
现在我使用的 for header 权限(已安装)这个包 https://github.com/barryvdh/laravel-cors在我的 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,
];
对于那些不使用 Laravel 的人
像这样设置标题:
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
部分,如果你只是使用*
这是行不通的!您需要设置标题名称。
希望能帮助到你。
Update
为了避免错误忘记提及301
你需要删除/
从你的 api url 末尾开始。
// my api (before)
https://example.com/api/categories/
//changed to
https://example.com/api/categories