一、建立中间件
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);
}
});
},