Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

laravel - I got No 'Access-Control-Allow-Origin' header is present on the requested resource error

Making request from @vue/cli 4.5.8 app to my laravel ( Laravel Framework 8.24.0 with hosting http://local-backend-currencies.com ) backendpoint app I got error in the console

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.

On client part :

console.log('+login settingCredentialsConfig::')
console.log(settingCredentialsConfig)

axios.post(apiUrl + '/login', userCredentials, settingCredentialsConfig)
  .then((response) => {

settingCredentialsConfig is defined :

export const settingCredentialsConfig = {
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Credentials': true
    // Authorization: -1
  }
}

and in src/main.js :

import axios from 'axios'
axios.defaults.crossDomain = true

and on laravel part in composer.json:

"license": "MIT",
    "require": {
    "php": "^7.3",
    "fruitcake/laravel-cors": "^2.0",
    "tymon/jwt-auth": "^1.0",
},

In config/auth.php :

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
        'hash' => false,
    ],

],

In app/Http/Kernel.php :

<?php

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        FruitcakeCorsHandleCors::class,  // I ADDED THIS LINE
        AppHttpMiddlewareTrustHosts::class,
        AppHttpMiddlewareTrustProxies::class,
        AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            'throttle:api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
    ];

    protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,


        'jwt.auth' => 'TymonJWTAuthMiddlewareGetUserFromToken', // I ADDED THIS LINE
        'jwt.refresh' => 'TymonJWTAuthMiddlewareRefreshToken'   // I ADDED THIS LINE
    ];
}

In config/cors.php :

<?php

return [


    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],


    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

I cleared cahce and dumped composer.

What did I miss ?

Thanks!

question from:https://stackoverflow.com/questions/65872326/i-got-no-access-control-allow-origin-header-is-present-on-the-requested-resour

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One easiest way to do this is by adding this code to the beginning of your API route file (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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...