在每个API请求nuxtJS上接收CORS策略错误



我试图运行Laravel V8.14(后端(和nuxtJS 2.15(前端(应用程序,但不幸的是,每个API请求(包括SSR请求(都会在我的LOCAL计算机上使用WAMP 获取CORS策略错误

运行npm run dev,所有内容都被编译并开始侦听http://localhost:3000/。当我试图访问主页时,控制台或命令提示符上没有错误。但是api请求获取CORS策略错误。我尝试过使用nuxtJS的baseURL和proxy,但错误一直保持不变。我知道你不能同时拥有这两个

Laravelcors.php配置文件

<?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS Options
|--------------------------------------------------------------------------
|
| The allowed_methods and allowed_headers options are case-insensitive.
|
| You don't need to provide both allowed_origins and allowed_origins_patterns.
| If one of the strings passed matches, it is considered a valid origin.
|
| If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
| all methods / origins / headers are allowed.
|
*/
/*
* You can enable CORS for 1 or multiple paths.
* Example: ['api/*']
*/
'paths' => ['api/*'],
/*
* Matches the request method. `[*]` allows all methods.
*/
'allowed_methods' => ['*'],
/*
* Matches the request origin. `[*]` allows all origins. Wildcards can be used, eg `*.mydomain.com`
*/
'allowed_origins' => ['*'],
/*
* Patterns that can be used with `preg_match` to match the origin.
*/
'allowed_origins_patterns' => [],
/*
* Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
*/
'allowed_headers' => ['*'],
/*
* Sets the Access-Control-Expose-Headers response header with these headers.
*/
'exposed_headers' => [],
/*
* Sets the Access-Control-Max-Age response header when > 0.
*/
'max_age' => 0,
/*
* Sets the Access-Control-Allow-Credentials header.
*/
'supports_credentials' => false,
];

nuxt.config.js文件

axios:{
//baseURL : process.env.CLIENT_URL, //Cant be used with proxy
proxy:true,
browserBaseURL: process.env.CLIENT_URL + '/api', // client url
prefix: '/api/',
common: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*',
}
},
proxy: {
'/api/': { target: 'http://api.localhost/', pathRewrite: {'^/api/': ''}, changeOrigin: true }
},

LaravelKernel.php

<?php
namespace AppHttp;
use IlluminateFoundationHttpKernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
FruitcakeCorsHandleCors::class,
AppHttpMiddlewareTrustProxies::class,
AppHttpMiddlewareCheckForMaintenanceMode::class,
IlluminateFoundationHttpMiddlewareValidatePostSize::class,
AppHttpMiddlewareTrimStrings::class,
IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
AppHttpMiddlewareSetLocale::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
// AppHttpMiddlewareEncryptCookies::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
// IlluminateSessionMiddlewareStartSession::class,
IlluminateSessionMiddlewareAuthenticateSession::class,
// IlluminateViewMiddlewareShareErrorsFromSession::class,
// AppHttpMiddlewareVerifyCsrfToken::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
'minify' =>[
RenatoMarinhoLaravelPageSpeedMiddlewareInlineCss::class,
RenatoMarinhoLaravelPageSpeedMiddlewareElideAttributes::class,
RenatoMarinhoLaravelPageSpeedMiddlewareInsertDNSPrefetch::class,
RenatoMarinhoLaravelPageSpeedMiddlewareRemoveComments::class,
RenatoMarinhoLaravelPageSpeedMiddlewareTrimUrls::class,
RenatoMarinhoLaravelPageSpeedMiddlewareRemoveQuotes::class,
RenatoMarinhoLaravelPageSpeedMiddlewareCollapseWhitespace::class,
],
'api' => [
//'throttle:60,1',
'bindings',

],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'admin' => AppHttpMiddlewareAdminmiddleware::class,
'auth' => AppHttpMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
IlluminateSessionMiddlewareStartSession::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
AppHttpMiddlewareAuthenticate::class,
IlluminateSessionMiddlewareAuthenticateSession::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
IlluminateAuthMiddlewareAuthorize::class,
];
}

精确错误

Access to XMLHttpRequest at 'http://localhost/api/dashboard/getusercompanyfresh'
from origin 'http://localhost:3000' 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.

所有API请求都在路由文件夹中的laravel-API.php中

我已经被困了5天了,大部分时间我都在用代理更换东西,希望下次能正常工作。我甚至全新安装了nuxtJS(删除了node_modules和package.json.lock(,但运气不佳。

如有任何帮助,我们将不胜感激。

您可以检查是否有任何异常响应,如die(...)dd(..)exit。这些方法也可能触发cors错误。

问题是我的wampapache配置,我将解释我采取的步骤,以找出导致CORS错误的原因以及我如何修复它。

在新窗口上安装完所有内容后,我仍然面临这个问题,但不是在实时服务器上,所以我认为它一定是我正在运行的web服务器,这就是问题所在。我在WAMP上的apache配置的错误部分是:

DocumentRoot "${INSTALL_DIR}/www/laravel/"
<Directory "${INSTALL_DIR}/www/laravel/">

我在httpd.confhttpsvhosts.conf中都有。在将上述内容更改为(添加laravel的公用文件夹(后:

DocumentRoot "${INSTALL_DIR}/www/laravel/public"
<Directory "${INSTALL_DIR}/www/laravel/public">

在我发布的问题中,一切都开始使用SAME配置,CORS策略错误消失了。

我还测试了另一种方法,你可以删除代理,nuxt.config.js文件中的axios设置如下:

axios:{
baseURL : process.env.CLIENT_URL, //Cant be used with proxy
browserBaseURL: process.env.CLIENT_URL + '/api', // client url
common: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*',
}
},

其中CLIENT_URL是.env laravel文件变量,在我的情况下其值为http://localhost,任何与代理相关的内容都应该注释,因为不能同时使用代理和baseURL。

阅读更多关于nuxt axios模块在这里

请记住,您也必须在httpd.conf 中取消注释LoadModule headers_module modules/mod_headers.so(也称为headers_module(

感谢一路上的所有帮助

相关内容

  • 没有找到相关文章

最新更新