zoukankan      html  css  js  c++  java
  • Vue.js2 + Laravel5 采用 CORS 方式解决 AJAX 跨域的问题

    一、建立中间件

    php artisan make:middleware CorsAjax

    二、编写中间件 CorsAjax

    <?php

    namespace AppHttpMiddleware;

    use Closure;

    class CorsAjax
    {
    /**
    * Handle an incoming request.
    *
    * @param IlluminateHttpRequest $request
    * @param Closure $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Methods: *");
    header("Access-Control-Allow-Headers: Content-Type,Access-Token");
    header("Access-Control-Expose-Headers: *");

    return $next($request);
    }
    }
    三、注册中间件 Kernel.php
    protected $routeMiddleware = [
    'authorize' => AppHttpMiddlewareauthorize_middleware::class,
    'common' => AppHttpMiddlewarecommon::class,
    'cors' => AppHttpMiddlewareCorsAjax::class,
    ];
    四、在路由中应用中间件
    /**
    * API 调用
    */
    Route::group([
    'middleware' => ['cors'],
    'prefix' => 'api',
    ], function () {
    Route::any('/', function () {
    $result = [
    'App' => '回家吃饭',
    'Version' => '1.0.1'
    ];
    return $result;
    });

    Route::any('/cab/getpagelist', function () {
    $cab = new Appcab();
    $params = $_GET;
    $result = $cab->getpagelist($params);
    return response($result, 200);
    });
    });
    五、运行后端 Laravel http服务
    假设域名为 foo.com
    六、运行前端 http 服务
    npm run dev
    七、可以在组件中 (.vue)使用 AJAX 跨域访问了
    代码如下:
    getDataRemote: function () {
    let self = this;
    let url = 'http://foo.com/api/cab/getpagelist';
    let params = {
    field: self.field,
    keyword: self.keyword
    };
    this.$axios
    .get(url, {
    params: params
    })
    .then(function (response) {
    let data = response.data;
    if (data.total > 0) {
    self.page += 1;
    self.cabData.rows = _.union(self.cabData.rows, response.data.rows);
    }
    });
    },




  • 相关阅读:
    springcloud中常用的注解
    MySQL--Profiling和Trace使用
    MySQL Execution Plan--IN查询计划
    MySQL Config--参数system_time_zone和参数time_zone
    MySQL Replication--全局参数gtid_executed和gtid_purged
    MySQL Transaction--事务无法正常回滚导致的异常
    MySQL Execution Plan--数据排序操作
    MySQL Session--批量KILL会话
    MySQL Transaction--MySQL与SQL Server在可重复读事务隔离级别上的差异
    MySQL Transaction--事务相关查询
  • 原文地址:https://www.cnblogs.com/mouseleo/p/8203656.html
Copyright © 2011-2022 走看看