Yii2 dont load all assets after setting baseUrl option - yii2

I need to set baseUrl option to 'admin' for my site.
'request' => [
'csrfParam' => '_csrf-backend',
'baseUrl' => '/admin'
],
After that all assets did not loaded with 404 error code.
http://localhost/admin/assets/e8a33efa/css/bootstrap.css
How to set correct baseUrl for assets?

Pls add content your asset file, which did not loaded.
also pls check if file exist in current folder:
/admin/assets/e8a33efa/css/bootstrap.css.
If file not exist pls try clear all content in /admin/runtime folder and /admin/web/assets folder and refresh the page

Related

Swagger run locally but not on IIS, not resolving base path

I am setting up Swagger for documenting my API.
I have set up the SwaggerEndpoint with a relative path the the specification json, like you see below:
When I debug locally, everything resolves fine. But my site just runs as http://localhost:44348/index.html.
When I deploy to IIS, which is on a virtual path, it blows apart:
Note that the URL in the browser has /imaging4castapi_UAT/ as part of the path
Note that the actual request for the swagger.json is missing that base part of the path.
Here's what I've tried:
I tried removing the RoutePrefix override. But that doesn't resolve.
I tried using an application path like "~/swagger/..." but that's translated by the server on view elements like Razor pages and css and doesn't work here in Startup.
I'm struggling to understand if this is a client setup issue or something related to how my site is hosted on IIS.
Thoughts?
Try using a relative path:
setupAction.SwaggerEndpoint("../swagger/Imaging4CastApiSpecification/swagger.json", "4Cast API");
Please note answer and explanation from the following issue: SwashBuckle
Here is my Swagger config for once of PRD application. Hope it helps
public static IServiceCollection AddSwaggerConfig(this IServiceCollection services, IHostingEnvironment env,
string title, string version)
=> services.AddSwaggerGen(c =>
{
//Ensure XML Document File of project is checked for both Debug and Release mode
c.IncludeXmlComments("Your App.xml");
//Display Enum name
c.DescribeAllEnumsAsStrings();
//c.OperationFilter<AddRequiredHeaderParameter>();
//Authentication for Bearer
c.AddSecurityDefinition("Bearer",
new ApiKeyScheme
{
In = "header",
Description = "Please enter JWT with Bearer into field",
Name = "Authorization",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer", Enumerable.Empty<string>()}
});
c.SwaggerDoc(version, new Info
{
Title = title,
Version = version,
Description = "",
Contact = new Contact
{
Email = "Support#ABC.com",
Name = ""
}
});
});
Startup file
app.
//Swagger
.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"./{_version}/swagger.json", Title);
});
The version is app variable from Config file which will be filtered by CI/CD
Swagger does not support Virtual Directory by default. Try and add this to your Startup.cs
app.UseSwagger(c =>
{
c.RouteTemplate = "virtual_path/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
//Include virtual directory
c.RoutePrefix = "virtual_path";// add your virtual path here.
c.SwaggerEndpoint("v1/swagger.json", "Api v1");
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"./v1/swagger.json", "Api v1");
});
My fix was following Killnines last comment to remove the preceding forward slash so that it looks like the following;
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("swagger/v1/swagger.json", "Your API v1");
});

How can I check the load and existence of the module (Yii2)?

I generated module siteadmin using GII, it appeared in the frontend/module folder. Next, I added it in the main.php front-end configuration file
'siteadmin' => [
'class' => 'app\modules\siteadmin\Module',
],
But the domain.net/siteadmin address shows a 404 error. Individual routs in the urlManager for this address are not created. How can I check all, and understand what is wrong and where is the error? Debug panel works, but it says: route to run: site/error
Try using explicit frontend application name eg:
'siteadmin' => [
'class' => 'frontend\modules\siteadmin\Module',
],
You need to confirm the namespace of the module class if you generated that module for the frontend the module class file frontend/modules/siteadmin/Siteadmin.php should have the namespace like.
namespace frontend\modules\siteadmin;
and the directory structure should look like below
The Siteadmin.php file that you are seeing in the above picture is the main module file.
If the directory structure is like I stated above in the picture then you should add the module inside the frontend/config/main.php like below
'modules' => [
'siteadmin' => [
'class' => 'frontend\modules\siteadmin\Siteadmin',
],
],
Then you can access it like http://example.com/siteadmin/default or if there is any other controller than default you can provide that name.

angular2 serving local JSON file via http.get while having custom routing rules

I am very new to Angular and running into an issue while trying to get a local .json file via http.get. This is due to my routing rules but I'm not sure how to fix it.
Directory Structure:
api
mockAppointments.json
app
app.component.*
scheduler
scheduler.component.*
scheduler.component.ts where http.get() call is made:
getAppointments() {
return this.http
.get('api/mockAppointments.json')
.map((response : Response) => <Appointment[]>response.json().data)
.catch(this.handleError);
}
Routing rules:
const appRoutes: Routes = [
{
path: 'scheduler',
component: SchedulerComponent
},
{
path: '',
redirectTo: '/scheduler',
pathMatch: 'full'
}
];
As I browse to http://localhost:4200/scheduler, the page loads as expected but dev console has the error:
GET http://localhost:4200/api/mockAppointments.json 404 (Not Found)
When I try to get to that URL by typing it in the browser, I see the following in dev console:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL
Segment: 'api/mockAppointments.json'
So it's clear that the issue is with routing. For now I need all URLs redirected to /scheduler (which is happening). When I make a http.get('api/mockAppointments.json') call, it should just serve that as is, almost like a pass through. Everything I have looked at, I would need a component to go along with any routing rule. That is fine, but there wouldn't be a template associated with it.
I have tried putting the api folder under assets but it made no difference.
Eventually the api call would be external to the app so this wouldn't be an issue but how do I get it working during development?
TLDR: Is it possible to have a 'pass through' route which serves a JSON file as is via http.get() ?
copy your api folder into assets folder. Angular can only access files from assets folder.
getAppointments() {
return this.http
.get('assets/api/mockAppointments.json')
.map((response : Response) => <Appointment[]>response.json().data)
.catch(this.handleError);
}

Yii2 minifying asset bundles throws error on external library

I've setup my asset bundles and am trying to run the asset console command to minify my JS and CSS files and it throws an error on one of my bundles that uses an external library
'file_get_contents(/httpdocs/site-name/frontend-test/assets/e4efadb7/https://maps.googleapis.com/maps/api/js?key=&libraries=&language=): failed to open stream: No such file or directory'
the Asset file in question is as follows:
public $sourcePath = '#frontend/assets/web';
public $css = [
//'css/site.css',
];
public $js = [
'js/google_map.js',
'https://maps.googleapis.com/maps/api/js?key=&libraries=&language='
];
public $depends = [
'frontend\assets\AppAsset',
];
If I remove the external library, it all works fine but then, as you would expect, the page doesn't load properly.
Is there a method to get the asset console command to understand absolute urls? or should I just include this with a call to registerJSFile ?
UPDATE:
I tried creating a blank js file locally so that the compression runs through correctly and then changing the mapping in the config files as follows:-
'assetManager' => [
'assetMap' => [
'js/googleapis.js' => 'https://maps.googleapis.com/maps/api/js?key=&libraries=&language='
],
...
]
But of course it won't load as it's all compressed and not trying to load js/googleapis.js!
I've had to resort to loading using registerJsFile but this seems messy. I was hoping Asset bundles would keep payloads together! Oh Well ...

Get shared link through Google Drive API

I am working on an app using Google Drive. I want the user to be able to share files by link, setting the permissions to anyone and withLink as described in the Google Developers documentation.
However, I cannot figure out what link to share. When I share a file in the Google Drive browser interface, I see the Link to share in the format:
https://docs.google.com/presentation/d/[...]/edit?usp=sharing
A link in this format is not part of the file resource object, nor it is returned from the http call setting the permissions. I hope someone can explain to me how to get this link through the REST api?
You can use the alternateLink property in the File resource to get a link that can be shared for opening the file in the relevant Google editor or viewer:
https://developers.google.com/drive/v2/reference/files
Update
[With API V3](https://developers.google.com/drive/api/v3/reference/files it is suggested to use the webViewLink property.
To actually enable link sharing using Google Drive API:
drive.permissions.create({
fileId: '......',
requestBody: {
role: 'reader',
type: 'anyone',
}
});
Get the webLinkView value using:
const webViewLink = await drive.files.get({
fileId: file.id,
fields: 'webViewLink'
}).then(response =>
response.data.webViewLink
);
In my case using the PHP Api v3, for the link to be non-empty you must define that you request this field... and if you have the right permissions:
so something like this:
$file =self::$service->files->get("1ogXyGxcJdMXt7nJddTpVqwd6_G8Hd5sUfq4b4cxvotest",array("fields"=>"webViewLink"));
Here's a practical example on how to get the WebViewLink file property (A.K.A. File edit link):
$file = $service->files->get($file_id, array('fields' => 'webViewLink'));
$web_link_view = $file->getWebViewLink();
OR
$sheetsList = $drive_service->files->listFiles([
'fields' => 'files(id, name, webViewLink, webContentLink)',
]);
$web_link_view = $sheetsList->current()->getWebViewLink();
Pay attention that you should load the file specifying which fields you wanna bring with it (In this case, webViewLink). If you don't do that, only id and name will be available.
In case you need to adjust the file sharing settings, this is how you do it:
$permissions = new \Google_Service_Drive_Permission();
$permissions->setRole('writer');
$permissions->setType('anyone');
$drive_service->permissions->create($file_id, $permissions);
Possible values for setRole() and setType() can be found here: https://developers.google.com/drive/api/v3/reference/permissions/create
For python, I only needed to get the file "id".
Then "created" the link like this:
def create_folder(folder_name, folder_id):
"""Create a folder and prints the folder ID and Folder link
Returns : Folder Id
"""
try:
# create drive api client
service = build("drive", "v3", credentials=creds)
file_metadata = {
"name": folder_name,
"mimeType": "application/vnd.google-apps.folder",
"parents": [folder_id],
}
file = (
service.files().create(body=file_metadata, fields="id").execute()
)
id = file.get("id")
print(
f'Folder ID: "{id}".',
f'https://drive.google.com/drive/u/0/folders/{id}',
)
return id
except HttpError as error:
print(f"An error occurred: {error}")
return None