Axios被laravel 7 cors阻止,没有“访问控制允许源头”

z9ju0rcb  于 2023-01-17  发布在  iOS
关注(0)|答案(4)|浏览(166)

我有一个后端应用程序与Laravel 7和前端的工作与VueJs。我的Laravel应用程序运行在laradock(nginx,postgres等...)使用 Postman 的API(Laravel 7)工作正常。
此API通过dns或ip进行应答。http://192.168.0.3:80/api/mobilehttp://laraapi.com/api/mobile
当我还在开发VueJs应用程序时,我使用"npm run serve"运行它,它提供了两种访问应用程序的方式,第一种是通过本地主机,第二种是通过IP地址,这两种方式都运行在8081端口。
当Axios使用使用GET动词的API时,一切正常。当Axios使用POST动词时,会出现get错误。
CORS策略已阻止从源"http://192.168.0.3:8081"访问位于"http://larapi.com/api/mobile/startorder/"的XMLHttpRequest:请求的资源上不存在"Access-Control-Allow-Origin"标头。
默认情况下,laravel 7已经为"Fruitcake"提供了CORS的预配置
所以我的kernel. php是这样的:

protected $middleware = [
    \Fruitcake\Cors\HandleCors::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

水果蛋糕被移到第一个,从另一个堆栈溢出,这没有帮助无论如何小费。
我的cors配置:

'paths' => ['*'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => false,

'max_age' => false,

'supports_credentials' => true,

查看supports_credentials和allow_origins是否已更改。无论如何,将allow_origins更改为"*"不起作用。
我已经创建了另一个名为"mobile"的路由文件,我用这个文件代替"api.php",内容是:

Route::group(['middleware' => 'auth:api'], function(){
    Route::namespace('Mobile')->group(function () {
        Route::post('startorder',
            ['as' => 'startorder', 'uses' => 'PRC\PurchaseController@startOrder']);
    });
});

创建这个新文件是因为我们的想法是将api.php用于其他目的。
我已经尝试在VueJs端设置代理,但不幸的是,结果是相同的。

    • Axios呼叫**
import { http } from "./config";
    startOrder: (order, user, token) => {
        var data = {
          "order": order,
          "user": user,      
        }
        return http.post("startorder/",data, {
          headers: {
            Authorization: "Bearer " + token,
            "Content-Type": "application/json",
          },
          withCredentials: true,
        });
      }
    • 我的配置js**
import axios from "axios";

export const http = axios.create({
  baseURL: "http://192.168.0.3:80/api/mobile/",
  withCredentials: true
});
    • 查看配置js**
module.exports = {
    devServer: {
        proxy: "http://192.168.0.3:80/api/mobile/",
        open: process.platform === 'darwin',
        host: '0.0.0.0',
        port: 8081, 
        https: false,
        hotOnly: false,
      },
    chainWebpack: config => {
        config
            .plugin('html')
            .tap(args => {
                args[0].title = 'LaraAPi'
                return args
            })
    }
}

当然,有些东西是失踪,但实际上我不知道哪一边是错误的了很多尝试后。
如果有人能帮我解决这个问题,我将不胜感激。

rdrgkggo

rdrgkggo1#

如果你使用axios withCredentials = true你需要启用laravel cros.php文件supports_credentials = true

对于axios代码示例:

axios.get('/user?ID=12345', { withCredentials: true })
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

用于cros.php代码示例

[
'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true
]
vyu0f0g1

vyu0f0g12#

我不知道'*'的东西。记住,这是非常糟糕的生产实践!
CORS策略已阻止从源"http://192.168.0.3:8081"访问位于"http://larapi.com/api/mobile/startorder/"的XMLHttpRequest:请求的资源上不存在"Access-Control-Allow-Origin"标头。
尝试将失败的原点放入cors.php

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

'allowed_origins' => ['http://192.168.0.3:8081', 'http://192.168.0.3:80', 'http://laraapi.com'],

允许以上所有三个源向此端点发出请求。
我们总是建议创建一个环境变量来更好地控制这种类型的配置。如果你让它在开发中工作,它也会自动在生产中工作!

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

'allowed_origins' => env('CORS_ALLOWED_ORIGINS'),

.环境

CORS_ALLOWED_ORIGINS=http://192.168.0.3:8081,http://192.168.0.3:80,http://laraapi.com

相应地更新生产.env文件。

uurv41yg

uurv41yg3#

    • cors.php**强烈建议您更改路径
<?php

退回]

/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/

'paths' => ['*'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => false,

'max_age' => false,

'supports_credentials' => false,

];

    • 内核. php**
<?php

namespace App\Http;

use App\Http\Middleware\cors;
use Illuminate\Foundation\Http\Kernel 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 = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];
/**
 * The application's route middleware groups.
 *
 * @var array
 */
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:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::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,
];

}

    • mobile. php(类似于api.php)**
<?php
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length');
header('Access-Control-Allow-Origin: http://192.168.0.4:8081');
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('login', 'Mobile\Login\UserController@login');
Route::post('register', 'Mobile\Login\UserController@register');

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
    • 视图侧**
//const configureAPI = require('./src/server/configure')

module.exports = {
    devServer: {
        proxy: "http://192.168.0.4:80/api/mobile/",
        open: process.platform === 'darwin',
        host: '0.0.0.0',
        port: 8081, // CHANGE YOUR PORT HERE!
        https: false,
        hotOnly: false,
      }
}
    • 配置js**
import axios from "axios";

export const http = axios.create({
  baseURL: "http://192.168.0.4:80/api/mobile/",
  withCredentials: false
});
    • 服务. js(使用API)**
start: (parameter, token) => {
    var data = {
      parameter: parameter,
      user: user,
    };
    return http.post("start/", data, {
      headers: {
        Authorization: "Bearer " + token,
        "Content-Type": "application/json",
      },
      withCredentials: false,
    });
  },

@Keith Gulbro我希望这能帮助你解决那个噩梦。如果你需要别的东西,让我知道。

enyaitl3

enyaitl34#

伙计们,看来这个问题至少现在已经解决了。我会继续寻找更好的解决办法。
下面是如何解决这个问题的详细信息。

1-从内核.php上受保护的中间件中删除\Fruitcake\Cors\HandleCors::类
2 -在API路由文件的标题上,您必须设置以下行:

header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length');
header('Access-Control-Allow-Origin: http://192.168.0.3:8081');

在我的例子中,我去掉了通配符 * 并输入了我的有效源。

3 -我已将Axios发布方法更改为使用假凭据发送。

export default {
login: data => {
    return http.post("login",data, {
      headers: {
        "Content-Type": "application/json",
      },
      withCredentials: false,
    });
  },

4 -已清除配置和缓存。

php artisan config:clear
php artisan cache:clear

现在响应头被正确地完成了,访问控制允许起源错误消失了。无论如何,使用FruitCake可能有一个更好的解决方案,否则提供一个低效的包是没有意义的。
如果有人有更好的解决方案,请分享!
谢谢

相关问题