您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
webman-中间件-跨域请求中间件(允许跨域配置)
发布时间:2022-01-19 22:38:42编辑:雪饮阅读()
允许一个接口路由跨域的路由配置config/route.php:
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use Webman\Route;
//允许跨域
Route::get('/blog/index', [app\controller\Foo::class, 'index'])->middleware([app\middleware\AccessControlTest::class]);
//默认不允许跨域
Route::post('/blog/login', [app\controller\Foo::class, 'login']);
Route::get('/blog/loginPage', [app\controller\Foo::class, 'loginPage']);
Route::fallback(function(){
return json(['code' => 404, 'msg' => '404 not found']);
});
允许跨域的中间件\app\middleware\AccessControlTest.php:
<?php
namespace app\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class AccessControlTest implements MiddlewareInterface
{
public function process(Request $request, callable $next) : Response
{
$response = $request->method() == 'OPTIONS' ? response('') : $next($request);
$response->withHeaders([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type,Authorization,X-Requested-With,Accept,Origin'
]);
return $response;
}
}
uniapp在8080端口请求http://localhost:8080/#/pages/index/index请求到8787端口的实现:
uni.request({
url: 'http://192.168.31.53:8787/blog/index',
success: (res) => {
console.log("res.data",res.data);
}
});
关键字词:webman,中间件,跨域,请求
上一篇:webman-路由-路由自动解析