Vue.js2 + Laravel5 采用 CORS 方式解決 AJAX 跨域的問題


一、建立中間件

php artisan make:middleware CorsAjax

二、編寫中間件 CorsAjax

<?php

namespace App\Http\Middleware;

use Closure;

class CorsAjax
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $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' => \App\Http\Middleware\authorize_middleware::class,
'common' => \App\Http\Middleware\common::class,
'cors' => \App\Http\Middleware\CorsAjax::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 \App\cab();
$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);
}
});
},





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM