我得到 No 'Access-Control-Allow-Origin' header is present on the requested resource error
Posted
技术标签:
【中文标题】我得到 No \'Access-Control-Allow-Origin\' header is present on the requested resource error【英文标题】:I got No 'Access-Control-Allow-Origin' header is present on the requested resource error我得到 No 'Access-Control-Allow-Origin' header is present on the requested resource error 【发布时间】:2021-04-28 12:34:30 【问题描述】:从@vue/cli 4.5.8 应用程序向我的 laravel 发出请求(Laravel Framework 8.24.0 与 主持http://local-backend-currencies.com) 后端应用程序我在控制台中遇到错误
Access to XMLHttpRequest at 'http://local-backend-currencies.com/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在客户端部分:
console.log('+login settingCredentialsConfig::')
console.log(settingCredentialsConfig)
axios.post(apiUrl + '/login', userCredentials, settingCredentialsConfig)
.then((response) =>
settingCredentialsConfig 已定义:
export const settingCredentialsConfig =
withCredentials: true,
headers:
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
// Authorization: -1
在 src/main.js 中:
import axios from 'axios'
axios.defaults.crossDomain = true
在 composer.json 中的 laravel 部分:
"license": "MIT",
"require":
"php": "^7.3",
"fruitcake/laravel-cors": "^2.0",
"tymon/jwt-auth": "^1.0",
,
在 config/auth.php 中:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
在 app/Http/Kernel.php 中:
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
protected $middleware = [
\Fruitcake\Cors\HandleCors::class, // I ADDED THIS LINE
\App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken', // I ADDED THIS LINE
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken' // I ADDED THIS LINE
];
在 config/cors.php 中:
<?php
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
我清除了 cahce 并抛弃了作曲家。
我错过了什么?
谢谢!
【问题讨论】:
Access-Control-*
标头是响应标头。您的服务器发送它们。在您的 php 配置文件中,您通过指定 paths
将它们限制为以 /api
开头的 url。但是您正在尝试请求一个没有该 /api 模式的 url。
当您在 development
环境中时,您的 apiUrl
看起来需要有所不同。你解决了这个检查process.env.NODE_ENV
变量
我在哪里设置 /api 模式?
是的,我在 .env.production 的 local-backend-currencies.com/api 的 url 中丢失了“/api”。谢谢!
【参考方案1】:
这是因为您想通过 JS 从本地主机访问远程位置 http://local-backend-currencies.com
- 这是被禁止的。
要拨打login
,您应该拨打http://localhost:8080/login
。我认为您从本地开发环境 localhost:8080
调用 Laravel 后端 - 这是一个坏主意。
我不确定 CORS 是如何在您的应用程序中设置的,您使用什么包,但如果真的一切正常,您应该允许 localhost:8080
。如果您使用 Laravel 7+,请参阅docs 了解此内容。
【讨论】:
不,包括 ttp://local-backend-currencies.com 在内的所有网站都在 apache 2 下的 1 个本地系统上 但是请求来自http://localhost:8080
。它在您发布的错误消息中清楚地说明了这一点。
这是一种以@vue/cli 4.5.8 为前端,laravel 为后端的应用程序【参考方案2】:
一种最简单的方法是将此代码添加到 API 路由文件 (api.php) 的开头
//header parameters to allow external server to access
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization, Accept, X-Requested-With');
【讨论】:
以上是关于我得到 No 'Access-Control-Allow-Origin' header is present on the requested resource error的主要内容,如果未能解决你的问题,请参考以下文章
为啥我得到 java.net.MalformedURLException: no protocol?
为啥我得到 AttributeError: Object has no attribute? [关闭]
为啥我得到 AttributeError: Object has no attribute? [关闭]
按照芹菜教程,我得到这个错误 No module named 'src'
我得到 No 'Access-Control-Allow-Origin' header is present on the requested resource error