Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

Yii2添加request的baseUrl后加载的资源url也会加上这个baseUrl导致加载的不对

我的是Advanced版本,我frontend和backend是单独用不同域名的,由于怕权限管理里面跟前台的路由有相同的,所以就在后台的路径里添加个/admin

具体是在backend的main.phpcomponents里添加baseUrl => /admin添加,添加后,页面是可以访问的,就是url多了个admin,比如从backend.example.com/controller/action变成backend.example.com/admin/controller/action

'components' => [
    'request' => [
        'csrfParam' => '_csrf-backend',
        //All requests will add "/admin",e.g:
        //backend.example.com/controller/action will change to
        //backend.example.com/admin/controller/action
        'baseUrl' => '/admin',
    ],
],

但问题是,assets url也加了这个admin,导致无法加载
image.png

我试了改这个文件backend/assets/AppAsset.php里的$baseUrl,但是无论我怎么修改,它完全不起作用(没设置'baseUrl' => '/admin'的时候设置这个是有用的)

<?php

namespace backendassets;

use yiiwebAssetBundle;

/**
 * Main backend application asset bundle.
 */
class AppAsset extends AssetBundle {
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
    
    ];
    public $depends = [
        'yiiwebYiiAsset',
        'yiibootstrapBootstrapAsset',
    ];
}

另外我发现在views页面中用registerJsFile()添加的js,就不会添加/admin,就能正常加载

$this->registerJsFile('plugins/ImageViewer/imageviewer.min.js', ['position' => View::POS_END, 'depends'=>JqueryAsset::class]);

image.png

所以想问一下大佬们,怎样设置能让assets不添加这个/admin?感觉这个文件backend/assets/AppAsset.php里应该可以设置才对呀。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

好吧,经过大量的搜索、仔细的查看文档以及Q群问网友,最后还是我自己解决了,如下代码所示,在components里面添加一个assetManager(必须小写开头),在里面就可以重置baseUrl

'components' => [
    'assetManager' => [
        //after settting components.request.baseUrl='/admin', the assets url will automatically add "/admin" to its url
        //to avoid this, we can set the asset baseUrl in components.assetManager.baseUrl, set it to '/assets'
        'baseUrl' => '/assets',
    ],
    'request' => [
        'csrfParam' => '_csrf-backend',
        //All requests will add "/admin",e.g:
        //www.example.com/controller/action will change to
        //www.example.com/admin/controller/action
        'baseUrl' => '/admin',
    ],
    // other configs....
],

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...