javascript - 请求的资源上存在 Vue js Access-Control-Allow-Origin' 标头
问题描述
我有一个在前端运行 Vue 的 laravel 应用程序。该应用程序在 localhost:8000 上运行,在 Vue 端,我正在尝试从另一个 API 获取数据,例如https://someapi.com/。但是,我收到此错误,Access to XMLHttpRequest at 'https://someapi.com/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
关于错误的研究让我想到了这个解决方案、这个和这个以及其他解决方案,但没有一个对我有用。
我创建了中间件:
<?php namespace App\Http\Middleware;
use Closure;
class CORS
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if ($request->getMethod() == "OPTIONS") {
return response()->make('OK', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
}
然后将其添加到 Kernel.php 中的 routemiddleware 数组中:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cors' => \App\Http\Middleware\CORS::class,
];
然后用它保护欢迎路线:
Route::middleware(['auth','cors'])->group(function () {
Route::get('/', function () {
return view('welcome');
});
});
解决方案
推荐阅读
- c# - 检索身份列 ADO.net 时出现问题
- linux - 查找包,包括 cronjob 或其他自动化脚本
- javascript - 明文字段不清空输入值
- c# - AutoMapper - 将数据从 Dto 复制到嵌套 Dto
- python - 如何提取href
- dart - Dart:如何创建一个聚合来自另一个流的事件的流?
- mongodb - MongoDB $project 嵌入文档到根级别以及另一个文档中的其他字段
- python - redis.exceptions.ConnectionError:连接到 localhost:6379 时出现错误 111。拒绝连接
- javascript - 为什么烧瓶应用程序在重新加载后不更新浏览?
- python - 如何部署一个简单的 Tkinter python 程序?