Explore all Meta Tags open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Meta Tags

meta-tags

v2.15.0

seotools

Small bug fix and adjusts

meta

v2.2.25

social-share

Laravel 9 support

djangocms-page-meta

1.0.1

Popular Libraries in Meta Tags

meta-tags

by kpumuk doticonrubydoticon

star image 2467 doticonMIT

Search Engine Optimization (SEO) for Ruby on Rails applications.

seotools

by artesaos doticonphpdoticon

star image 2449 doticonMIT

SEO Tools for Laravel

meta

by mateodelnorte doticonjavascriptdoticon

star image 1608 doticonMIT

tool for turning many repos into a meta repo. why choose many repos or a monolithic repo, when you can have both with a meta repo?

vue-head

by ktquez doticonjavascriptdoticon

star image 962 doticonMIT

Manager the meta information of the head tag, a simple and easy way

vue-headful

by troxler doticonjavascriptdoticon

star image 232 doticonMIT

Set document title and meta tags with Vue.js

social-share

by prodeveloper doticonphpdoticon

star image 181 doticonMIT

Sharing to Social Networks for Laravel 5

laravel-Meta

by eusonlito doticonjavascriptdoticon

star image 152 doticonMIT

HTML Meta Tags management package available for for Laravel 5.*

meta-mender

by mendersoftware doticonpythondoticon

star image 127 doticonNOASSERTION

Yocto Project meta layer for the Mender client

laravel-meta-manager

by davmixcool doticonphpdoticon

star image 91 doticonMIT

Laravel Meta Manager is an SEO tool that is used to improve SEO of a website or specific page by adding recommended meta tags to your application.

Trending New libraries in Meta Tags

laravel-auto-head-tags

by area17 doticonphpdoticon

star image 43 doticonMIT

Laravel auto head tags

InterviewFAANG

by BaseMax doticonpythondoticon

star image 22 doticonGPL-3.0

Solving Facebook interview questions.

kirby3-seo

by HashandSalt doticonphpdoticon

star image 8 doticon

A plugin for generating SEO meta tags

image-meta-feature-extractor

by gabrieljaguiar doticonpythondoticon

star image 7 doticon

An image meta-feature extractor for meta-learning tasks.

SEO_Linter

by Eshy10 doticonrubydoticon

star image 4 doticon

The Linter is for beginners who are not familiar with the SEO HTML tag rules. There are so many rules for SEO HTML tag but this linter focus on the basic requirement to have a good SEO HTML tag. It provides feedback if they do not observe the SEO HTML tag rule.

MetaScrapper

by hojabbr doticonphpdoticon

star image 4 doticon

Laravel package to get all the meta data from a URL

meta-ebaz4205

by embed-me doticoncdoticon

star image 3 doticonGPL-3.0

meta-layer for EBAZ4205

metapatcher

by muratgozel doticonjavascriptdoticon

star image 2 doticonMIT

HTML document head management including meta tags, social media tags, icons and JSONLD expressions across devices.

metagetall

by piyushsi doticonjavascriptdoticon

star image 2 doticonMIT

A Node.js module to fetch HTML meta tags and custom meta tags from a remote URL.

Top Authors in Meta Tags

1

kplaube

2 Libraries

star icon8

2

ITPrism

1 Libraries

star icon4

3

craft-machine

1 Libraries

star icon7

4

ryanlfoster

1 Libraries

star icon8

5

NicheOffice

1 Libraries

star icon2

6

Torann

1 Libraries

star icon6

7

endonde

1 Libraries

star icon2

8

eusonlito

1 Libraries

star icon152

9

pedroborges

1 Libraries

star icon38

10

runtimerevolution

1 Libraries

star icon2

1

2 Libraries

star icon8

2

1 Libraries

star icon4

3

1 Libraries

star icon7

4

1 Libraries

star icon8

5

1 Libraries

star icon2

6

1 Libraries

star icon6

7

1 Libraries

star icon2

8

1 Libraries

star icon152

9

1 Libraries

star icon38

10

1 Libraries

star icon2

Trending Kits in Meta Tags

No Trending Kits are available at this moment for Meta Tags

Trending Discussions on Meta Tags

Server side rendering not working with modules lazy loading angular 12 on live server

Border on top bar on mobile safari

Adding onclick function in anchor tag which is not working

images not appear in the blade page if send it to email by using queue job Laravel?

FirebaseOptions cannot be null when creating the default app

Wrong og:image is appearing on page metadata

React js change meta tags dynamically

Why is blazor HeadOutlet rendering after the App

Can't link flutter web application to firebase project / infinite loading

Error when creating custom dashboard using WooCommerce REST API

QUESTION

Server side rendering not working with modules lazy loading angular 12 on live server

Asked 2022-Mar-06 at 11:12

On the localhost module, lazy loading is working fine, showing meta tags and HTML content in <app-root><app-root/> in the view page source, but it is not showing on the live server. On the live server, I can only see meta tags and HTML contents of components that are direct children of AppModule but lazy loaded modules components are not showing meta tags and HTML. This weird behavior is only on the live server.

app.server.module.ts

1 import { NgModule } from '@angular/core';
2    import { ServerModule } from '@angular/platform-server';
3    import { AppComponent } from './app.component';
4    import { AppModule } from './app.module';
5    
6    @NgModule({
7        imports: [AppModule, ServerModule],
8        bootstrap: [AppComponent]
9    })
10    export class AppServerModule { }
11

main.server.ts

1 import { NgModule } from '@angular/core';
2    import { ServerModule } from '@angular/platform-server';
3    import { AppComponent } from './app.component';
4    import { AppModule } from './app.module';
5    
6    @NgModule({
7        imports: [AppModule, ServerModule],
8        bootstrap: [AppComponent]
9    })
10    export class AppServerModule { }
11import '@angular/localize/init'
12import '@angular/platform-server/init';
13
14import { enableProdMode } from '@angular/core';
15
16import { environment } from './environments/environment';
17
18if (environment.production) {
19  enableProdMode();
20}
21
22export { AppServerModule } from './app/app.server.module';
23export { renderModule } from '@angular/platform-server';
24

server.ts

1 import { NgModule } from '@angular/core';
2    import { ServerModule } from '@angular/platform-server';
3    import { AppComponent } from './app.component';
4    import { AppModule } from './app.module';
5    
6    @NgModule({
7        imports: [AppModule, ServerModule],
8        bootstrap: [AppComponent]
9    })
10    export class AppServerModule { }
11import '@angular/localize/init'
12import '@angular/platform-server/init';
13
14import { enableProdMode } from '@angular/core';
15
16import { environment } from './environments/environment';
17
18if (environment.production) {
19  enableProdMode();
20}
21
22export { AppServerModule } from './app/app.server.module';
23export { renderModule } from '@angular/platform-server';
24import '@angular/localize/init';
25import 'zone.js/dist/zone-node';
26import 'reflect-metadata';
27import { ngExpressEngine } from '@nguniversal/express-engine';
28import * as express from 'express';
29import { join } from 'path';
30
31import { AppServerModule } from './src/main.server';
32import { APP_BASE_HREF } from '@angular/common';
33import { existsSync, readFileSync } from 'fs';
34import { createWindow } from 'domino';
35import 'localstorage-polyfill'
36import 'localstorage-polyfill'
37const scripts = readFileSync('dist/clientWeb/browser/index.html').toString();
38const window = createWindow(scripts) as any;
39(global as any).window = window;
40(global as any).document = window.document;
41(global as any).Event = window.Event;
42(global as any).KeyboardEvent = window.KeyboardEvent;
43(global as any).MouseEvent = window.MouseEvent;
44
45// The Express app is exported so that it can be used by serverless Functions.
46export function app(): express.Express {
47  const server = express();
48  const distFolder = join(process.cwd(), 'dist/clientWeb/browser');
49  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
50
51  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
52  server.engine('html', ngExpressEngine({
53    bootstrap: AppServerModule,
54  }));
55
56  server.set('view engine', 'html');
57  server.set('views', distFolder);
58
59  // Example Express Rest API endpoints
60  // server.get('/api/**', (req, res) =&gt; { });
61  // Serve static files from /browser
62  server.get('*.*', express.static(distFolder, {
63    maxAge: '1y'
64  }));
65
66  // All regular routes use the Universal engine
67  server.get('*', (req, res) =&gt; {
68    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
69  });
70
71  return server;
72}
73
74function run(): void {
75  const port = process.env['PORT'] || 4000;
76
77  // Start up the Node server
78  const server = app();
79  server.listen(port, () =&gt; {
80    console.log(`Node Express server listening on http://localhost:${port}`);
81  });
82}
83const MockBrowser = require('mock-browser').mocks.MockBrowser;
84const mock = new MockBrowser();
85(global as any).localStorage = localStorage;
86
87// Webpack will replace 'require' with '__webpack_require__'
88// '__non_webpack_require__' is a proxy to Node 'require'
89// The below code is to ensure that the server is run only when not requiring the bundle.
90declare const __non_webpack_require__: NodeRequire;
91const mainModule = __non_webpack_require__.main;
92const moduleFilename = mainModule &amp;&amp; mainModule.filename || '';
93if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
94  run();
95}
96
97export * from './src/main.server';
98

app.modules.ts

1 import { NgModule } from '@angular/core';
2    import { ServerModule } from '@angular/platform-server';
3    import { AppComponent } from './app.component';
4    import { AppModule } from './app.module';
5    
6    @NgModule({
7        imports: [AppModule, ServerModule],
8        bootstrap: [AppComponent]
9    })
10    export class AppServerModule { }
11import '@angular/localize/init'
12import '@angular/platform-server/init';
13
14import { enableProdMode } from '@angular/core';
15
16import { environment } from './environments/environment';
17
18if (environment.production) {
19  enableProdMode();
20}
21
22export { AppServerModule } from './app/app.server.module';
23export { renderModule } from '@angular/platform-server';
24import '@angular/localize/init';
25import 'zone.js/dist/zone-node';
26import 'reflect-metadata';
27import { ngExpressEngine } from '@nguniversal/express-engine';
28import * as express from 'express';
29import { join } from 'path';
30
31import { AppServerModule } from './src/main.server';
32import { APP_BASE_HREF } from '@angular/common';
33import { existsSync, readFileSync } from 'fs';
34import { createWindow } from 'domino';
35import 'localstorage-polyfill'
36import 'localstorage-polyfill'
37const scripts = readFileSync('dist/clientWeb/browser/index.html').toString();
38const window = createWindow(scripts) as any;
39(global as any).window = window;
40(global as any).document = window.document;
41(global as any).Event = window.Event;
42(global as any).KeyboardEvent = window.KeyboardEvent;
43(global as any).MouseEvent = window.MouseEvent;
44
45// The Express app is exported so that it can be used by serverless Functions.
46export function app(): express.Express {
47  const server = express();
48  const distFolder = join(process.cwd(), 'dist/clientWeb/browser');
49  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
50
51  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
52  server.engine('html', ngExpressEngine({
53    bootstrap: AppServerModule,
54  }));
55
56  server.set('view engine', 'html');
57  server.set('views', distFolder);
58
59  // Example Express Rest API endpoints
60  // server.get('/api/**', (req, res) =&gt; { });
61  // Serve static files from /browser
62  server.get('*.*', express.static(distFolder, {
63    maxAge: '1y'
64  }));
65
66  // All regular routes use the Universal engine
67  server.get('*', (req, res) =&gt; {
68    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
69  });
70
71  return server;
72}
73
74function run(): void {
75  const port = process.env['PORT'] || 4000;
76
77  // Start up the Node server
78  const server = app();
79  server.listen(port, () =&gt; {
80    console.log(`Node Express server listening on http://localhost:${port}`);
81  });
82}
83const MockBrowser = require('mock-browser').mocks.MockBrowser;
84const mock = new MockBrowser();
85(global as any).localStorage = localStorage;
86
87// Webpack will replace 'require' with '__webpack_require__'
88// '__non_webpack_require__' is a proxy to Node 'require'
89// The below code is to ensure that the server is run only when not requiring the bundle.
90declare const __non_webpack_require__: NodeRequire;
91const mainModule = __non_webpack_require__.main;
92const moduleFilename = mainModule &amp;&amp; mainModule.filename || '';
93if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
94  run();
95}
96
97export * from './src/main.server';
98import { BrowserModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG, Title } from '@angular/platform-browser';
99import { FormsModule, ReactiveFormsModule } from '@angular/forms';
100import { AppComponent } from './app.component';
101import { AppLayoutComponent } from './shared/layout/app-layout/app-layout.component';
102import { NgModule, CUSTOM_ELEMENTS_SCHEMA, ModuleWithProviders } from '@angular/core';
103import { RouterModule, Routes } from '@angular/router';
104import { AppRoutingModule } from './app-routing.module';
105import { HttpClientModule } from '@angular/common/http';
106import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
107import { Tradesmanapplayout2Component } from './shared/layout/tradesmanapplayout2/tradesmanapplayout2.component';
108import { Supplierapplayout2Component } from './shared/layout/supplierapplayout2/supplierapplayout2.component';
109import { Userapplayout2Component } from './shared/layout/userapplayout2/userapplayout2.component';
110import { AppDasboardHeader2Component } from './shared/layout/app-dasboard-header2/app-dasboard-header2.component';
111import { AppDasboardFooter2Component } from './shared/layout/app-dasboard-footer2/app-dasboard-footer2.component';
112
113const routes: Routes = [
114
115  {
116    path: 'resetpassword',
117    component: AppHeaderLayoutComponent,
118    loadChildren: () =&gt; import('./common/resetPassword/resetpassword.module').then(m =&gt; m.ResetpasswordModule)
119  },
120  {
121    path: 'Supplier',
122    component: Userapplayout2Component,
123    loadChildren: () =&gt; import('./supplier/supplier.module').then(m =&gt; m.SupplierModule),
124    
125  },
126  {
127    path: 'User',
128    component: Userapplayout2Component,
129    loadChildren: () =&gt; import('./user/user.module').then(m =&gt; m.UserModule),
130  
131  },
132  {
133    path: 'MarketPlace',
134    //component: UsersApplayoutComponent,
135    //component: AppHeaderLayoutComponent,
136    component: Userapplayout2Component,
137    loadChildren: () =&gt; import('./marketplace/marketplace.module').then(m =&gt; m.MarketplaceModule),
138  },
139  {
140    path: 'User/Agrements',
141    //component: AppLayoutComponent,
142    component: AppHeaderLayoutComponent,
143
144    loadChildren: () =&gt; import('./agrements/agrements.module').then(m =&gt; m.AgrementsModule)
145  },
146  {
147    path: 'HWUser',
148    //component: AppLayoutComponent,
149    component: AppHeaderLayoutComponent,
150    loadChildren: () =&gt; import('./HelpAndFAQ/helpQuestion.module').then(m =&gt; m.HelpQuestionModule)
151  },
152  {
153    path: 'Tradesman',
154    component: Userapplayout2Component,
155    loadChildren: () =&gt; import('./trademan/trademan.module').then(m =&gt; m.TrademanModule),
156    canActivate: [AuthGuardTradesmanService],
157    canActivateChild: [AuthGuardTradesmanService]
158  },
159  {
160    path: 'ContactUs',
161    //component: AppLayoutComponent,
162    component: AppHeaderLayoutComponent,
163    loadChildren: () =&gt; import('./contactUs/contactUs.module').then(m =&gt; m.ContactUsModule)
164  },
165  {
166    path: 'landing-page/liveleads',
167    //component: AppLayoutComponent,
168    component: AppHeaderLayoutComponent,
169    loadChildren: () =&gt; import('./landing-page/liveleads/liveleads.module').then(m =&gt; m.LiveleadsModule)
170  },
171  {
172    path: 'landing-page',
173    component: AppHeaderLayoutComponent,
174    loadChildren: () =&gt; import('./landing-page/landing-page.module').then(m =&gt; m.LandingPageModule)
175  }
176]
177
178@NgModule({
179  declarations: [
180    AppComponent,
181    AppLayoutComponent,
182    AppDasboardHeaderComponent,
183    AppDasboardFooterComponent,
184    AppLeftmenuComponent,
185    AppcommonfooterComponent,
186    SupplierLayoutComponent,
187    TrademanLayoutComponent,
188    TrademenuLeftComponent,
189    SupplierLeftmenuComponent,
190  ],
191  imports: [
192    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
193    NgbModule,
194    RouterModule.forRoot(routes, { enableTracing: false }),
195    ModalModule.forRoot(),
196    HttpModule,
197    BrowserAnimationsModule,
198    NgxImageCompressService,
199    Events,
200    Title,
201    metaTagsService,
202    ShareService,
203
204  ],
205  schemas: [
206    CUSTOM_ELEMENTS_SCHEMA
207  ],
208  bootstrap: [AppComponent]
209})
210export class AppModule { }
211

Deployed Web.config on IIS

1 import { NgModule } from '@angular/core';
2    import { ServerModule } from '@angular/platform-server';
3    import { AppComponent } from './app.component';
4    import { AppModule } from './app.module';
5    
6    @NgModule({
7        imports: [AppModule, ServerModule],
8        bootstrap: [AppComponent]
9    })
10    export class AppServerModule { }
11import '@angular/localize/init'
12import '@angular/platform-server/init';
13
14import { enableProdMode } from '@angular/core';
15
16import { environment } from './environments/environment';
17
18if (environment.production) {
19  enableProdMode();
20}
21
22export { AppServerModule } from './app/app.server.module';
23export { renderModule } from '@angular/platform-server';
24import '@angular/localize/init';
25import 'zone.js/dist/zone-node';
26import 'reflect-metadata';
27import { ngExpressEngine } from '@nguniversal/express-engine';
28import * as express from 'express';
29import { join } from 'path';
30
31import { AppServerModule } from './src/main.server';
32import { APP_BASE_HREF } from '@angular/common';
33import { existsSync, readFileSync } from 'fs';
34import { createWindow } from 'domino';
35import 'localstorage-polyfill'
36import 'localstorage-polyfill'
37const scripts = readFileSync('dist/clientWeb/browser/index.html').toString();
38const window = createWindow(scripts) as any;
39(global as any).window = window;
40(global as any).document = window.document;
41(global as any).Event = window.Event;
42(global as any).KeyboardEvent = window.KeyboardEvent;
43(global as any).MouseEvent = window.MouseEvent;
44
45// The Express app is exported so that it can be used by serverless Functions.
46export function app(): express.Express {
47  const server = express();
48  const distFolder = join(process.cwd(), 'dist/clientWeb/browser');
49  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
50
51  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
52  server.engine('html', ngExpressEngine({
53    bootstrap: AppServerModule,
54  }));
55
56  server.set('view engine', 'html');
57  server.set('views', distFolder);
58
59  // Example Express Rest API endpoints
60  // server.get('/api/**', (req, res) =&gt; { });
61  // Serve static files from /browser
62  server.get('*.*', express.static(distFolder, {
63    maxAge: '1y'
64  }));
65
66  // All regular routes use the Universal engine
67  server.get('*', (req, res) =&gt; {
68    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
69  });
70
71  return server;
72}
73
74function run(): void {
75  const port = process.env['PORT'] || 4000;
76
77  // Start up the Node server
78  const server = app();
79  server.listen(port, () =&gt; {
80    console.log(`Node Express server listening on http://localhost:${port}`);
81  });
82}
83const MockBrowser = require('mock-browser').mocks.MockBrowser;
84const mock = new MockBrowser();
85(global as any).localStorage = localStorage;
86
87// Webpack will replace 'require' with '__webpack_require__'
88// '__non_webpack_require__' is a proxy to Node 'require'
89// The below code is to ensure that the server is run only when not requiring the bundle.
90declare const __non_webpack_require__: NodeRequire;
91const mainModule = __non_webpack_require__.main;
92const moduleFilename = mainModule &amp;&amp; mainModule.filename || '';
93if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
94  run();
95}
96
97export * from './src/main.server';
98import { BrowserModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG, Title } from '@angular/platform-browser';
99import { FormsModule, ReactiveFormsModule } from '@angular/forms';
100import { AppComponent } from './app.component';
101import { AppLayoutComponent } from './shared/layout/app-layout/app-layout.component';
102import { NgModule, CUSTOM_ELEMENTS_SCHEMA, ModuleWithProviders } from '@angular/core';
103import { RouterModule, Routes } from '@angular/router';
104import { AppRoutingModule } from './app-routing.module';
105import { HttpClientModule } from '@angular/common/http';
106import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
107import { Tradesmanapplayout2Component } from './shared/layout/tradesmanapplayout2/tradesmanapplayout2.component';
108import { Supplierapplayout2Component } from './shared/layout/supplierapplayout2/supplierapplayout2.component';
109import { Userapplayout2Component } from './shared/layout/userapplayout2/userapplayout2.component';
110import { AppDasboardHeader2Component } from './shared/layout/app-dasboard-header2/app-dasboard-header2.component';
111import { AppDasboardFooter2Component } from './shared/layout/app-dasboard-footer2/app-dasboard-footer2.component';
112
113const routes: Routes = [
114
115  {
116    path: 'resetpassword',
117    component: AppHeaderLayoutComponent,
118    loadChildren: () =&gt; import('./common/resetPassword/resetpassword.module').then(m =&gt; m.ResetpasswordModule)
119  },
120  {
121    path: 'Supplier',
122    component: Userapplayout2Component,
123    loadChildren: () =&gt; import('./supplier/supplier.module').then(m =&gt; m.SupplierModule),
124    
125  },
126  {
127    path: 'User',
128    component: Userapplayout2Component,
129    loadChildren: () =&gt; import('./user/user.module').then(m =&gt; m.UserModule),
130  
131  },
132  {
133    path: 'MarketPlace',
134    //component: UsersApplayoutComponent,
135    //component: AppHeaderLayoutComponent,
136    component: Userapplayout2Component,
137    loadChildren: () =&gt; import('./marketplace/marketplace.module').then(m =&gt; m.MarketplaceModule),
138  },
139  {
140    path: 'User/Agrements',
141    //component: AppLayoutComponent,
142    component: AppHeaderLayoutComponent,
143
144    loadChildren: () =&gt; import('./agrements/agrements.module').then(m =&gt; m.AgrementsModule)
145  },
146  {
147    path: 'HWUser',
148    //component: AppLayoutComponent,
149    component: AppHeaderLayoutComponent,
150    loadChildren: () =&gt; import('./HelpAndFAQ/helpQuestion.module').then(m =&gt; m.HelpQuestionModule)
151  },
152  {
153    path: 'Tradesman',
154    component: Userapplayout2Component,
155    loadChildren: () =&gt; import('./trademan/trademan.module').then(m =&gt; m.TrademanModule),
156    canActivate: [AuthGuardTradesmanService],
157    canActivateChild: [AuthGuardTradesmanService]
158  },
159  {
160    path: 'ContactUs',
161    //component: AppLayoutComponent,
162    component: AppHeaderLayoutComponent,
163    loadChildren: () =&gt; import('./contactUs/contactUs.module').then(m =&gt; m.ContactUsModule)
164  },
165  {
166    path: 'landing-page/liveleads',
167    //component: AppLayoutComponent,
168    component: AppHeaderLayoutComponent,
169    loadChildren: () =&gt; import('./landing-page/liveleads/liveleads.module').then(m =&gt; m.LiveleadsModule)
170  },
171  {
172    path: 'landing-page',
173    component: AppHeaderLayoutComponent,
174    loadChildren: () =&gt; import('./landing-page/landing-page.module').then(m =&gt; m.LandingPageModule)
175  }
176]
177
178@NgModule({
179  declarations: [
180    AppComponent,
181    AppLayoutComponent,
182    AppDasboardHeaderComponent,
183    AppDasboardFooterComponent,
184    AppLeftmenuComponent,
185    AppcommonfooterComponent,
186    SupplierLayoutComponent,
187    TrademanLayoutComponent,
188    TrademenuLeftComponent,
189    SupplierLeftmenuComponent,
190  ],
191  imports: [
192    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
193    NgbModule,
194    RouterModule.forRoot(routes, { enableTracing: false }),
195    ModalModule.forRoot(),
196    HttpModule,
197    BrowserAnimationsModule,
198    NgxImageCompressService,
199    Events,
200    Title,
201    metaTagsService,
202    ShareService,
203
204  ],
205  schemas: [
206    CUSTOM_ELEMENTS_SCHEMA
207  ],
208  bootstrap: [AppComponent]
209})
210export class AppModule { }
211&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
212&lt;configuration&gt;
213  &lt;location path=&quot;.&quot; inheritInChildApplications=&quot;false&quot;&gt;
214    &lt;system.webServer&gt;
215      &lt;handlers&gt;
216    &lt;add name=&quot;iisnode&quot; path=&quot;main.js&quot; verb=&quot;*&quot; modules=&quot;iisnode&quot;/&gt;
217      &lt;/handlers&gt;
218      &lt;aspNetCore processPath=&quot;dotnet&quot; arguments=&quot;.\HW.Web2.dll&quot; stdoutLogEnabled=&quot;false&quot; stdoutLogFile=&quot;.\logs\stdout&quot; /&gt;
219
220&lt;rewrite&gt;
221   &lt;rules&gt;
222        &lt;rule name=&quot;LogFile&quot; patternSyntax=&quot;ECMAScript&quot; stopProcessing=&quot;true&quot;&gt;
223             &lt;match url=&quot;iisnode&quot;/&gt;
224        &lt;/rule&gt;
225       
226        &lt;rule name=&quot;StaticContent&quot;&gt;
227             &lt;action type=&quot;Rewrite&quot; url=&quot;{{REQUEST_URI}}&quot;/&gt;
228        &lt;/rule&gt;
229        &lt;rule name=&quot;DynamicContent&quot;&gt;
230             &lt;conditions&gt;
231                  &lt;add input=&quot;{{REQUEST_FILENAME}}&quot; matchType=&quot;IsFile&quot; negate=&quot;True&quot;/&gt;
232             &lt;/conditions&gt;
233             &lt;action type=&quot;Rewrite&quot; url=&quot;main.js&quot;/&gt;
234        &lt;/rule&gt;
235   &lt;/rules&gt;
236 &lt;/rewrite&gt;
237 &lt;iisnode devErrorsEnabled=&quot;false&quot;
238  debuggingEnabled=&quot;false&quot;
239   loggingEnabled=&quot;false&quot; 
240   nodeProcessCommandLine=&quot;C:\Program Files\nodejs\node.exe&quot; /&gt;
241
242    &lt;/system.webServer&gt;
243  &lt;/location&gt;
244&lt;/configuration&gt;
245

ANSWER

Answered 2022-Mar-06 at 11:12

There are several reasons why the body tag of your angular app fails to render on the server side. Here's a checklist:

  • First make sure your live environment supports NodeJS. Without NodeJS on the server, you can't use server-side rendering
  • In Visual Studio, try changing your ASPNETCORE_ENVIRONMENT environment variable from DEVELOPMENT to PRODUCTION and run your application. In some cases the app behaves differently in either configuration (looks for the main.js file in another location when PRODUCTION). After starting the debugger and trying to prerender a view, you may see some exceptions in the Visual Studio Output window.
    • In my case the main.js file had to end up at ClientApp/dist/main.js. So I had to modify angular.json changing the projects:ClientApp:architect:build:options:outputPath to dist (see also)
  • If you experience this problem using Visual Studio, do always look at the Output window for errors which will point you in the right direction.
  • If you're hosting a PWA (for example through @angular/pwa), then it's totally normal that you're getting an empty page when going to View source in the browser. If you'd then ctrl + F5, you'll be bypassing the angular service worker which shows you the prerendered html source. This is something you shouldn't bother about. Google, Bing, ... will actually fetch and index the server-side rendered version of your page.
  • If you're using ASP.NET Core 3.1 or earlier, you cannot have an async lambda for your SupplyData delegate. SupplyData is not a Func<Task> and is not being awaited in the source code of ASP.NET Core. I changed this in my port to .NET 6
1 import { NgModule } from '@angular/core';
2    import { ServerModule } from '@angular/platform-server';
3    import { AppComponent } from './app.component';
4    import { AppModule } from './app.module';
5    
6    @NgModule({
7        imports: [AppModule, ServerModule],
8        bootstrap: [AppComponent]
9    })
10    export class AppServerModule { }
11import '@angular/localize/init'
12import '@angular/platform-server/init';
13
14import { enableProdMode } from '@angular/core';
15
16import { environment } from './environments/environment';
17
18if (environment.production) {
19  enableProdMode();
20}
21
22export { AppServerModule } from './app/app.server.module';
23export { renderModule } from '@angular/platform-server';
24import '@angular/localize/init';
25import 'zone.js/dist/zone-node';
26import 'reflect-metadata';
27import { ngExpressEngine } from '@nguniversal/express-engine';
28import * as express from 'express';
29import { join } from 'path';
30
31import { AppServerModule } from './src/main.server';
32import { APP_BASE_HREF } from '@angular/common';
33import { existsSync, readFileSync } from 'fs';
34import { createWindow } from 'domino';
35import 'localstorage-polyfill'
36import 'localstorage-polyfill'
37const scripts = readFileSync('dist/clientWeb/browser/index.html').toString();
38const window = createWindow(scripts) as any;
39(global as any).window = window;
40(global as any).document = window.document;
41(global as any).Event = window.Event;
42(global as any).KeyboardEvent = window.KeyboardEvent;
43(global as any).MouseEvent = window.MouseEvent;
44
45// The Express app is exported so that it can be used by serverless Functions.
46export function app(): express.Express {
47  const server = express();
48  const distFolder = join(process.cwd(), 'dist/clientWeb/browser');
49  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
50
51  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
52  server.engine('html', ngExpressEngine({
53    bootstrap: AppServerModule,
54  }));
55
56  server.set('view engine', 'html');
57  server.set('views', distFolder);
58
59  // Example Express Rest API endpoints
60  // server.get('/api/**', (req, res) =&gt; { });
61  // Serve static files from /browser
62  server.get('*.*', express.static(distFolder, {
63    maxAge: '1y'
64  }));
65
66  // All regular routes use the Universal engine
67  server.get('*', (req, res) =&gt; {
68    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
69  });
70
71  return server;
72}
73
74function run(): void {
75  const port = process.env['PORT'] || 4000;
76
77  // Start up the Node server
78  const server = app();
79  server.listen(port, () =&gt; {
80    console.log(`Node Express server listening on http://localhost:${port}`);
81  });
82}
83const MockBrowser = require('mock-browser').mocks.MockBrowser;
84const mock = new MockBrowser();
85(global as any).localStorage = localStorage;
86
87// Webpack will replace 'require' with '__webpack_require__'
88// '__non_webpack_require__' is a proxy to Node 'require'
89// The below code is to ensure that the server is run only when not requiring the bundle.
90declare const __non_webpack_require__: NodeRequire;
91const mainModule = __non_webpack_require__.main;
92const moduleFilename = mainModule &amp;&amp; mainModule.filename || '';
93if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
94  run();
95}
96
97export * from './src/main.server';
98import { BrowserModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG, Title } from '@angular/platform-browser';
99import { FormsModule, ReactiveFormsModule } from '@angular/forms';
100import { AppComponent } from './app.component';
101import { AppLayoutComponent } from './shared/layout/app-layout/app-layout.component';
102import { NgModule, CUSTOM_ELEMENTS_SCHEMA, ModuleWithProviders } from '@angular/core';
103import { RouterModule, Routes } from '@angular/router';
104import { AppRoutingModule } from './app-routing.module';
105import { HttpClientModule } from '@angular/common/http';
106import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
107import { Tradesmanapplayout2Component } from './shared/layout/tradesmanapplayout2/tradesmanapplayout2.component';
108import { Supplierapplayout2Component } from './shared/layout/supplierapplayout2/supplierapplayout2.component';
109import { Userapplayout2Component } from './shared/layout/userapplayout2/userapplayout2.component';
110import { AppDasboardHeader2Component } from './shared/layout/app-dasboard-header2/app-dasboard-header2.component';
111import { AppDasboardFooter2Component } from './shared/layout/app-dasboard-footer2/app-dasboard-footer2.component';
112
113const routes: Routes = [
114
115  {
116    path: 'resetpassword',
117    component: AppHeaderLayoutComponent,
118    loadChildren: () =&gt; import('./common/resetPassword/resetpassword.module').then(m =&gt; m.ResetpasswordModule)
119  },
120  {
121    path: 'Supplier',
122    component: Userapplayout2Component,
123    loadChildren: () =&gt; import('./supplier/supplier.module').then(m =&gt; m.SupplierModule),
124    
125  },
126  {
127    path: 'User',
128    component: Userapplayout2Component,
129    loadChildren: () =&gt; import('./user/user.module').then(m =&gt; m.UserModule),
130  
131  },
132  {
133    path: 'MarketPlace',
134    //component: UsersApplayoutComponent,
135    //component: AppHeaderLayoutComponent,
136    component: Userapplayout2Component,
137    loadChildren: () =&gt; import('./marketplace/marketplace.module').then(m =&gt; m.MarketplaceModule),
138  },
139  {
140    path: 'User/Agrements',
141    //component: AppLayoutComponent,
142    component: AppHeaderLayoutComponent,
143
144    loadChildren: () =&gt; import('./agrements/agrements.module').then(m =&gt; m.AgrementsModule)
145  },
146  {
147    path: 'HWUser',
148    //component: AppLayoutComponent,
149    component: AppHeaderLayoutComponent,
150    loadChildren: () =&gt; import('./HelpAndFAQ/helpQuestion.module').then(m =&gt; m.HelpQuestionModule)
151  },
152  {
153    path: 'Tradesman',
154    component: Userapplayout2Component,
155    loadChildren: () =&gt; import('./trademan/trademan.module').then(m =&gt; m.TrademanModule),
156    canActivate: [AuthGuardTradesmanService],
157    canActivateChild: [AuthGuardTradesmanService]
158  },
159  {
160    path: 'ContactUs',
161    //component: AppLayoutComponent,
162    component: AppHeaderLayoutComponent,
163    loadChildren: () =&gt; import('./contactUs/contactUs.module').then(m =&gt; m.ContactUsModule)
164  },
165  {
166    path: 'landing-page/liveleads',
167    //component: AppLayoutComponent,
168    component: AppHeaderLayoutComponent,
169    loadChildren: () =&gt; import('./landing-page/liveleads/liveleads.module').then(m =&gt; m.LiveleadsModule)
170  },
171  {
172    path: 'landing-page',
173    component: AppHeaderLayoutComponent,
174    loadChildren: () =&gt; import('./landing-page/landing-page.module').then(m =&gt; m.LandingPageModule)
175  }
176]
177
178@NgModule({
179  declarations: [
180    AppComponent,
181    AppLayoutComponent,
182    AppDasboardHeaderComponent,
183    AppDasboardFooterComponent,
184    AppLeftmenuComponent,
185    AppcommonfooterComponent,
186    SupplierLayoutComponent,
187    TrademanLayoutComponent,
188    TrademenuLeftComponent,
189    SupplierLeftmenuComponent,
190  ],
191  imports: [
192    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
193    NgbModule,
194    RouterModule.forRoot(routes, { enableTracing: false }),
195    ModalModule.forRoot(),
196    HttpModule,
197    BrowserAnimationsModule,
198    NgxImageCompressService,
199    Events,
200    Title,
201    metaTagsService,
202    ShareService,
203
204  ],
205  schemas: [
206    CUSTOM_ELEMENTS_SCHEMA
207  ],
208  bootstrap: [AppComponent]
209})
210export class AppModule { }
211&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
212&lt;configuration&gt;
213  &lt;location path=&quot;.&quot; inheritInChildApplications=&quot;false&quot;&gt;
214    &lt;system.webServer&gt;
215      &lt;handlers&gt;
216    &lt;add name=&quot;iisnode&quot; path=&quot;main.js&quot; verb=&quot;*&quot; modules=&quot;iisnode&quot;/&gt;
217      &lt;/handlers&gt;
218      &lt;aspNetCore processPath=&quot;dotnet&quot; arguments=&quot;.\HW.Web2.dll&quot; stdoutLogEnabled=&quot;false&quot; stdoutLogFile=&quot;.\logs\stdout&quot; /&gt;
219
220&lt;rewrite&gt;
221   &lt;rules&gt;
222        &lt;rule name=&quot;LogFile&quot; patternSyntax=&quot;ECMAScript&quot; stopProcessing=&quot;true&quot;&gt;
223             &lt;match url=&quot;iisnode&quot;/&gt;
224        &lt;/rule&gt;
225       
226        &lt;rule name=&quot;StaticContent&quot;&gt;
227             &lt;action type=&quot;Rewrite&quot; url=&quot;{{REQUEST_URI}}&quot;/&gt;
228        &lt;/rule&gt;
229        &lt;rule name=&quot;DynamicContent&quot;&gt;
230             &lt;conditions&gt;
231                  &lt;add input=&quot;{{REQUEST_FILENAME}}&quot; matchType=&quot;IsFile&quot; negate=&quot;True&quot;/&gt;
232             &lt;/conditions&gt;
233             &lt;action type=&quot;Rewrite&quot; url=&quot;main.js&quot;/&gt;
234        &lt;/rule&gt;
235   &lt;/rules&gt;
236 &lt;/rewrite&gt;
237 &lt;iisnode devErrorsEnabled=&quot;false&quot;
238  debuggingEnabled=&quot;false&quot;
239   loggingEnabled=&quot;false&quot; 
240   nodeProcessCommandLine=&quot;C:\Program Files\nodejs\node.exe&quot; /&gt;
241
242    &lt;/system.webServer&gt;
243  &lt;/location&gt;
244&lt;/configuration&gt;
245options.SupplyData = async (context, data) =&gt; { ... };
246
  • Some live environments block webrequests sent by your angular application during SSR, back to your server. In this case you will get an internal server error (500). You need to solve this by using OnSupplyData.
EDIT

My resulting web.config after deployment:

1 import { NgModule } from '@angular/core';
2    import { ServerModule } from '@angular/platform-server';
3    import { AppComponent } from './app.component';
4    import { AppModule } from './app.module';
5    
6    @NgModule({
7        imports: [AppModule, ServerModule],
8        bootstrap: [AppComponent]
9    })
10    export class AppServerModule { }
11import '@angular/localize/init'
12import '@angular/platform-server/init';
13
14import { enableProdMode } from '@angular/core';
15
16import { environment } from './environments/environment';
17
18if (environment.production) {
19  enableProdMode();
20}
21
22export { AppServerModule } from './app/app.server.module';
23export { renderModule } from '@angular/platform-server';
24import '@angular/localize/init';
25import 'zone.js/dist/zone-node';
26import 'reflect-metadata';
27import { ngExpressEngine } from '@nguniversal/express-engine';
28import * as express from 'express';
29import { join } from 'path';
30
31import { AppServerModule } from './src/main.server';
32import { APP_BASE_HREF } from '@angular/common';
33import { existsSync, readFileSync } from 'fs';
34import { createWindow } from 'domino';
35import 'localstorage-polyfill'
36import 'localstorage-polyfill'
37const scripts = readFileSync('dist/clientWeb/browser/index.html').toString();
38const window = createWindow(scripts) as any;
39(global as any).window = window;
40(global as any).document = window.document;
41(global as any).Event = window.Event;
42(global as any).KeyboardEvent = window.KeyboardEvent;
43(global as any).MouseEvent = window.MouseEvent;
44
45// The Express app is exported so that it can be used by serverless Functions.
46export function app(): express.Express {
47  const server = express();
48  const distFolder = join(process.cwd(), 'dist/clientWeb/browser');
49  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
50
51  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
52  server.engine('html', ngExpressEngine({
53    bootstrap: AppServerModule,
54  }));
55
56  server.set('view engine', 'html');
57  server.set('views', distFolder);
58
59  // Example Express Rest API endpoints
60  // server.get('/api/**', (req, res) =&gt; { });
61  // Serve static files from /browser
62  server.get('*.*', express.static(distFolder, {
63    maxAge: '1y'
64  }));
65
66  // All regular routes use the Universal engine
67  server.get('*', (req, res) =&gt; {
68    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
69  });
70
71  return server;
72}
73
74function run(): void {
75  const port = process.env['PORT'] || 4000;
76
77  // Start up the Node server
78  const server = app();
79  server.listen(port, () =&gt; {
80    console.log(`Node Express server listening on http://localhost:${port}`);
81  });
82}
83const MockBrowser = require('mock-browser').mocks.MockBrowser;
84const mock = new MockBrowser();
85(global as any).localStorage = localStorage;
86
87// Webpack will replace 'require' with '__webpack_require__'
88// '__non_webpack_require__' is a proxy to Node 'require'
89// The below code is to ensure that the server is run only when not requiring the bundle.
90declare const __non_webpack_require__: NodeRequire;
91const mainModule = __non_webpack_require__.main;
92const moduleFilename = mainModule &amp;&amp; mainModule.filename || '';
93if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
94  run();
95}
96
97export * from './src/main.server';
98import { BrowserModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG, Title } from '@angular/platform-browser';
99import { FormsModule, ReactiveFormsModule } from '@angular/forms';
100import { AppComponent } from './app.component';
101import { AppLayoutComponent } from './shared/layout/app-layout/app-layout.component';
102import { NgModule, CUSTOM_ELEMENTS_SCHEMA, ModuleWithProviders } from '@angular/core';
103import { RouterModule, Routes } from '@angular/router';
104import { AppRoutingModule } from './app-routing.module';
105import { HttpClientModule } from '@angular/common/http';
106import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
107import { Tradesmanapplayout2Component } from './shared/layout/tradesmanapplayout2/tradesmanapplayout2.component';
108import { Supplierapplayout2Component } from './shared/layout/supplierapplayout2/supplierapplayout2.component';
109import { Userapplayout2Component } from './shared/layout/userapplayout2/userapplayout2.component';
110import { AppDasboardHeader2Component } from './shared/layout/app-dasboard-header2/app-dasboard-header2.component';
111import { AppDasboardFooter2Component } from './shared/layout/app-dasboard-footer2/app-dasboard-footer2.component';
112
113const routes: Routes = [
114
115  {
116    path: 'resetpassword',
117    component: AppHeaderLayoutComponent,
118    loadChildren: () =&gt; import('./common/resetPassword/resetpassword.module').then(m =&gt; m.ResetpasswordModule)
119  },
120  {
121    path: 'Supplier',
122    component: Userapplayout2Component,
123    loadChildren: () =&gt; import('./supplier/supplier.module').then(m =&gt; m.SupplierModule),
124    
125  },
126  {
127    path: 'User',
128    component: Userapplayout2Component,
129    loadChildren: () =&gt; import('./user/user.module').then(m =&gt; m.UserModule),
130  
131  },
132  {
133    path: 'MarketPlace',
134    //component: UsersApplayoutComponent,
135    //component: AppHeaderLayoutComponent,
136    component: Userapplayout2Component,
137    loadChildren: () =&gt; import('./marketplace/marketplace.module').then(m =&gt; m.MarketplaceModule),
138  },
139  {
140    path: 'User/Agrements',
141    //component: AppLayoutComponent,
142    component: AppHeaderLayoutComponent,
143
144    loadChildren: () =&gt; import('./agrements/agrements.module').then(m =&gt; m.AgrementsModule)
145  },
146  {
147    path: 'HWUser',
148    //component: AppLayoutComponent,
149    component: AppHeaderLayoutComponent,
150    loadChildren: () =&gt; import('./HelpAndFAQ/helpQuestion.module').then(m =&gt; m.HelpQuestionModule)
151  },
152  {
153    path: 'Tradesman',
154    component: Userapplayout2Component,
155    loadChildren: () =&gt; import('./trademan/trademan.module').then(m =&gt; m.TrademanModule),
156    canActivate: [AuthGuardTradesmanService],
157    canActivateChild: [AuthGuardTradesmanService]
158  },
159  {
160    path: 'ContactUs',
161    //component: AppLayoutComponent,
162    component: AppHeaderLayoutComponent,
163    loadChildren: () =&gt; import('./contactUs/contactUs.module').then(m =&gt; m.ContactUsModule)
164  },
165  {
166    path: 'landing-page/liveleads',
167    //component: AppLayoutComponent,
168    component: AppHeaderLayoutComponent,
169    loadChildren: () =&gt; import('./landing-page/liveleads/liveleads.module').then(m =&gt; m.LiveleadsModule)
170  },
171  {
172    path: 'landing-page',
173    component: AppHeaderLayoutComponent,
174    loadChildren: () =&gt; import('./landing-page/landing-page.module').then(m =&gt; m.LandingPageModule)
175  }
176]
177
178@NgModule({
179  declarations: [
180    AppComponent,
181    AppLayoutComponent,
182    AppDasboardHeaderComponent,
183    AppDasboardFooterComponent,
184    AppLeftmenuComponent,
185    AppcommonfooterComponent,
186    SupplierLayoutComponent,
187    TrademanLayoutComponent,
188    TrademenuLeftComponent,
189    SupplierLeftmenuComponent,
190  ],
191  imports: [
192    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
193    NgbModule,
194    RouterModule.forRoot(routes, { enableTracing: false }),
195    ModalModule.forRoot(),
196    HttpModule,
197    BrowserAnimationsModule,
198    NgxImageCompressService,
199    Events,
200    Title,
201    metaTagsService,
202    ShareService,
203
204  ],
205  schemas: [
206    CUSTOM_ELEMENTS_SCHEMA
207  ],
208  bootstrap: [AppComponent]
209})
210export class AppModule { }
211&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
212&lt;configuration&gt;
213  &lt;location path=&quot;.&quot; inheritInChildApplications=&quot;false&quot;&gt;
214    &lt;system.webServer&gt;
215      &lt;handlers&gt;
216    &lt;add name=&quot;iisnode&quot; path=&quot;main.js&quot; verb=&quot;*&quot; modules=&quot;iisnode&quot;/&gt;
217      &lt;/handlers&gt;
218      &lt;aspNetCore processPath=&quot;dotnet&quot; arguments=&quot;.\HW.Web2.dll&quot; stdoutLogEnabled=&quot;false&quot; stdoutLogFile=&quot;.\logs\stdout&quot; /&gt;
219
220&lt;rewrite&gt;
221   &lt;rules&gt;
222        &lt;rule name=&quot;LogFile&quot; patternSyntax=&quot;ECMAScript&quot; stopProcessing=&quot;true&quot;&gt;
223             &lt;match url=&quot;iisnode&quot;/&gt;
224        &lt;/rule&gt;
225       
226        &lt;rule name=&quot;StaticContent&quot;&gt;
227             &lt;action type=&quot;Rewrite&quot; url=&quot;{{REQUEST_URI}}&quot;/&gt;
228        &lt;/rule&gt;
229        &lt;rule name=&quot;DynamicContent&quot;&gt;
230             &lt;conditions&gt;
231                  &lt;add input=&quot;{{REQUEST_FILENAME}}&quot; matchType=&quot;IsFile&quot; negate=&quot;True&quot;/&gt;
232             &lt;/conditions&gt;
233             &lt;action type=&quot;Rewrite&quot; url=&quot;main.js&quot;/&gt;
234        &lt;/rule&gt;
235   &lt;/rules&gt;
236 &lt;/rewrite&gt;
237 &lt;iisnode devErrorsEnabled=&quot;false&quot;
238  debuggingEnabled=&quot;false&quot;
239   loggingEnabled=&quot;false&quot; 
240   nodeProcessCommandLine=&quot;C:\Program Files\nodejs\node.exe&quot; /&gt;
241
242    &lt;/system.webServer&gt;
243  &lt;/location&gt;
244&lt;/configuration&gt;
245options.SupplyData = async (context, data) =&gt; { ... };
246&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
247&lt;configuration&gt;
248  &lt;location path=&quot;.&quot; inheritInChildApplications=&quot;false&quot;&gt;
249    &lt;system.webServer&gt;
250      &lt;modules runAllManagedModulesForAllRequests=&quot;false&quot;&gt;
251        &lt;remove name=&quot;WebDAVModule&quot; /&gt;
252      &lt;/modules&gt;
253      &lt;rewrite&gt;
254        &lt;rules&gt;
255          &lt;rule name=&quot;NonWwwRedirection&quot; stopProcessing=&quot;false&quot;&gt;
256            &lt;match url=&quot;.*&quot; /&gt;
257            &lt;conditions&gt;
258              &lt;add input=&quot;{HTTP_HOST}&quot; pattern=&quot;^www.mintplayer.com$&quot; /&gt;
259            &lt;/conditions&gt;
260            &lt;action type=&quot;Redirect&quot; url=&quot;https://mintplayer.com/{R:0}&quot; redirectType=&quot;Permanent&quot; /&gt;
261          &lt;/rule&gt;
262        &lt;/rules&gt;
263      &lt;/rewrite&gt;
264      &lt;httpProtocol&gt;
265        &lt;customHeaders&gt;
266          &lt;remove name=&quot;X-Powered-By&quot; /&gt;
267        &lt;/customHeaders&gt;
268      &lt;/httpProtocol&gt;
269      &lt;security&gt;
270        &lt;requestFiltering allowDoubleEscaping=&quot;false&quot;&gt;
271          &lt;requestLimits maxAllowedContentLength=&quot;30000000&quot; maxUrl=&quot;40960&quot; maxQueryString=&quot;20480&quot; /&gt;
272        &lt;/requestFiltering&gt;
273      &lt;/security&gt;
274      &lt;handlers&gt;
275        &lt;add name=&quot;aspNetCore&quot; path=&quot;*&quot; verb=&quot;*&quot; modules=&quot;AspNetCoreModuleV2&quot; resourceType=&quot;Unspecified&quot; /&gt;
276      &lt;/handlers&gt;
277      &lt;aspNetCore processPath=&quot;dotnet&quot; arguments=&quot;.\MintPlayer.Web.dll&quot; stdoutLogEnabled=&quot;false&quot; stdoutLogFile=&quot;.\logs\stdout&quot; hostingModel=&quot;inprocess&quot; /&gt;
278    &lt;/system.webServer&gt;
279  &lt;/location&gt;
280  &lt;system.web&gt;
281    &lt;compilation tempDirectory=&quot;......&quot; /&gt;
282  &lt;/system.web&gt;
283&lt;/configuration&gt;
284

Source https://stackoverflow.com/questions/71158747

QUESTION

Border on top bar on mobile safari

Asked 2022-Feb-19 at 08:55

I’m trying to get my website working properly and I’m having trouble with the top bar on iOS safari. The website in question is my personal site. And so far I’ve found the issue on the iPhone 11 Pro Max safari though I have reason to believe it is affecting all notched iPhones.

The problem in question

Is there any way to use css or meta tags in order to remove this line between the header and the top bar. I haven’t been able to find any info and so far the only work around I’ve found is to make it a web app. Though I doubt people would add my website to their Home Screen just to avoid the issue.

ANSWER

Answered 2021-Nov-18 at 21:03

You cannot remove this line with css, it is for the browser to separate the top bar from your website. If your header has a different background color, you wouldn't even notice. Take a look at this (It is on an iPhone with notch) :

enter image description here

Source https://stackoverflow.com/questions/70026229

QUESTION

Adding onclick function in anchor tag which is not working

Asked 2022-Jan-27 at 06:58

I am have made dropdown using bootstarap. I have added onlcick funtions in my anchor tags in dropdown. I just want make my text box readonly if one of the link is clicked on. I have used js to make text boxes read only. Please Help me to solve my problem. Below is my code:

1&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
2    pageEncoding=&quot;ISO-8859-1&quot;%&gt;
3&lt;!DOCTYPE html&gt;
4&lt;html&gt;
5&lt;head&gt;
6&lt;!-- Required meta tags --&gt;
7&lt;meta charset=&quot;utf-8&quot;&gt;
8&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
9
10&lt;!-- Bootstrap CSS --&gt;
11&lt;link
12    href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot;
13    rel=&quot;stylesheet&quot;
14    integrity=&quot;sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3&quot;
15    crossorigin=&quot;anonymous&quot;&gt;
16
17&lt;title&gt;Mole Calculator | Chemistry Calculator&lt;/title&gt;
18
19&lt;/head&gt;
20
21
22
23&lt;body&gt;
24
25    &lt;nav class=&quot;navbar fixed-top navbar-expand-lg navbar-dark bg-black&quot;&gt;
26
27        &lt;div class=&quot;container-fluid&quot;&gt;
28            &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;&lt;h4&gt;
29                    &lt;b&gt;Chemistry Calculator&lt;/b&gt;
30                &lt;/h4&gt;&lt;/a&gt;
31
32            &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot;
33                data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarSupportedContent&quot;
34                aria-controls=&quot;navbarSupportedContent&quot; aria-expanded=&quot;false&quot;
35                aria-label=&quot;Toggle navigation&quot;&gt;
36                &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
37            &lt;/button&gt;
38
39            &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarSupportedContent&quot;&gt;
40
41                &lt;ul class=&quot;navbar-nav  text-uppercase&quot;&gt;
42
43                    &lt;li class=&quot;nav-item&quot;&gt;&lt;a class=&quot;nav-link active&quot;
44                        aria-current=&quot;page&quot; href=&quot;/Chemistry-Calculator/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
45
46                    &lt;li class=&quot;nav-item&quot;&gt;&lt;a class=&quot;nav-link active&quot;
47                        aria-current=&quot;page&quot; href=&quot;/Chemistry-Calculator/about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;
48
49
50                &lt;/ul&gt;
51
52            &lt;/div&gt;
53        &lt;/div&gt;
54    &lt;/nav&gt;
55
56    &lt;div class=&quot;container&quot; style=&quot;padding-top: 5%;&quot;&gt;
57
58        &lt;div class=&quot;card px-4 py-5&quot; style=&quot;width: 650px;&quot;&gt;
59            &lt;div class=&quot;card-block&quot;&gt;
60
61                &lt;form action=&quot;/Chemistry-Calculator/Number-Of-Moles&quot;&gt;
62
63                    &lt;div class=&quot;mb-3&quot;&gt;
64                        &lt;label for=&quot;givenMass&quot; class=&quot;form-label&quot;&gt;Given Mass of
65                            Substance&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;givenMass&quot;
66                            aria-describedby=&quot;emailHelp&quot; name=&quot;givenMass&quot;
67                            value=&quot;${givenMass}&quot; style=&quot;width: 600px&quot;&gt;
68                    &lt;/div&gt;
69                    &lt;div class=&quot;mb-3&quot;&gt;
70                        &lt;label for=&quot;molarMass&quot; class=&quot;form-label&quot;&gt;Molar Mass&lt;/label&gt; &lt;input
71                            type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;molarMass&quot; name=&quot;molarMass&quot;
72                            value=&quot;${molarMass}&quot; style=&quot;width: 600px&quot;&gt;
73                    &lt;/div&gt;
74
75                    &lt;div class=&quot;mb-3&quot;&gt;
76                        &lt;label for=&quot;molarMass&quot; class=&quot;form-label&quot;&gt;Moles&lt;/label&gt; &lt;input
77                            type=&quot;text&quot;  class=&quot;form-control&quot;
78                            id=&quot;molarMass&quot; name=&quot;moles&quot; value=&quot;${moles}&quot; style=&quot;width: 600px&quot;&gt;
79                    &lt;/div&gt;
80
81                    &lt;input class=&quot;btn btn-outline-success&quot; type=&quot;submit&quot;
82                        value=&quot;Calculate&quot;&gt;
83                        
84                    &lt;div class=&quot;btn-group&quot;&gt;
85                        &lt;button type=&quot;button&quot; class=&quot;btn btn-success dropdown-toggle&quot;
86                            data-bs-toggle=&quot;dropdown&quot; aria-expanded=&quot;false&quot;&gt;Choose what to calculate &lt;/button&gt;
87                        &lt;ul class=&quot;dropdown-menu&quot;&gt;
88                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForMoles()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Moles&lt;/a&gt;&lt;/li&gt;
89                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForMolarMass()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Molar Mass&lt;/a&gt;&lt;/li&gt;
90                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForGivenMass()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Given mass&lt;/a&gt;&lt;/li&gt;
91                        &lt;/ul&gt;
92                    &lt;/div&gt;
93
94                &lt;/form&gt;
95            &lt;/div&gt;
96        &lt;/div&gt;
97    &lt;/div&gt;
98
99    &lt;script
100        src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js&quot;
101        integrity=&quot;sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p&quot;
102        crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
103    &lt;script type=&quot;text/javascript&quot; src=&quot;../javascript/script.js&quot;&gt;&lt;/script&gt;
104
105&lt;/body&gt;
106&lt;/html&gt;
107

My Java Script File:

1&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
2    pageEncoding=&quot;ISO-8859-1&quot;%&gt;
3&lt;!DOCTYPE html&gt;
4&lt;html&gt;
5&lt;head&gt;
6&lt;!-- Required meta tags --&gt;
7&lt;meta charset=&quot;utf-8&quot;&gt;
8&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
9
10&lt;!-- Bootstrap CSS --&gt;
11&lt;link
12    href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot;
13    rel=&quot;stylesheet&quot;
14    integrity=&quot;sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3&quot;
15    crossorigin=&quot;anonymous&quot;&gt;
16
17&lt;title&gt;Mole Calculator | Chemistry Calculator&lt;/title&gt;
18
19&lt;/head&gt;
20
21
22
23&lt;body&gt;
24
25    &lt;nav class=&quot;navbar fixed-top navbar-expand-lg navbar-dark bg-black&quot;&gt;
26
27        &lt;div class=&quot;container-fluid&quot;&gt;
28            &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;&lt;h4&gt;
29                    &lt;b&gt;Chemistry Calculator&lt;/b&gt;
30                &lt;/h4&gt;&lt;/a&gt;
31
32            &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot;
33                data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarSupportedContent&quot;
34                aria-controls=&quot;navbarSupportedContent&quot; aria-expanded=&quot;false&quot;
35                aria-label=&quot;Toggle navigation&quot;&gt;
36                &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
37            &lt;/button&gt;
38
39            &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarSupportedContent&quot;&gt;
40
41                &lt;ul class=&quot;navbar-nav  text-uppercase&quot;&gt;
42
43                    &lt;li class=&quot;nav-item&quot;&gt;&lt;a class=&quot;nav-link active&quot;
44                        aria-current=&quot;page&quot; href=&quot;/Chemistry-Calculator/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
45
46                    &lt;li class=&quot;nav-item&quot;&gt;&lt;a class=&quot;nav-link active&quot;
47                        aria-current=&quot;page&quot; href=&quot;/Chemistry-Calculator/about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;
48
49
50                &lt;/ul&gt;
51
52            &lt;/div&gt;
53        &lt;/div&gt;
54    &lt;/nav&gt;
55
56    &lt;div class=&quot;container&quot; style=&quot;padding-top: 5%;&quot;&gt;
57
58        &lt;div class=&quot;card px-4 py-5&quot; style=&quot;width: 650px;&quot;&gt;
59            &lt;div class=&quot;card-block&quot;&gt;
60
61                &lt;form action=&quot;/Chemistry-Calculator/Number-Of-Moles&quot;&gt;
62
63                    &lt;div class=&quot;mb-3&quot;&gt;
64                        &lt;label for=&quot;givenMass&quot; class=&quot;form-label&quot;&gt;Given Mass of
65                            Substance&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;givenMass&quot;
66                            aria-describedby=&quot;emailHelp&quot; name=&quot;givenMass&quot;
67                            value=&quot;${givenMass}&quot; style=&quot;width: 600px&quot;&gt;
68                    &lt;/div&gt;
69                    &lt;div class=&quot;mb-3&quot;&gt;
70                        &lt;label for=&quot;molarMass&quot; class=&quot;form-label&quot;&gt;Molar Mass&lt;/label&gt; &lt;input
71                            type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;molarMass&quot; name=&quot;molarMass&quot;
72                            value=&quot;${molarMass}&quot; style=&quot;width: 600px&quot;&gt;
73                    &lt;/div&gt;
74
75                    &lt;div class=&quot;mb-3&quot;&gt;
76                        &lt;label for=&quot;molarMass&quot; class=&quot;form-label&quot;&gt;Moles&lt;/label&gt; &lt;input
77                            type=&quot;text&quot;  class=&quot;form-control&quot;
78                            id=&quot;molarMass&quot; name=&quot;moles&quot; value=&quot;${moles}&quot; style=&quot;width: 600px&quot;&gt;
79                    &lt;/div&gt;
80
81                    &lt;input class=&quot;btn btn-outline-success&quot; type=&quot;submit&quot;
82                        value=&quot;Calculate&quot;&gt;
83                        
84                    &lt;div class=&quot;btn-group&quot;&gt;
85                        &lt;button type=&quot;button&quot; class=&quot;btn btn-success dropdown-toggle&quot;
86                            data-bs-toggle=&quot;dropdown&quot; aria-expanded=&quot;false&quot;&gt;Choose what to calculate &lt;/button&gt;
87                        &lt;ul class=&quot;dropdown-menu&quot;&gt;
88                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForMoles()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Moles&lt;/a&gt;&lt;/li&gt;
89                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForMolarMass()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Molar Mass&lt;/a&gt;&lt;/li&gt;
90                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForGivenMass()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Given mass&lt;/a&gt;&lt;/li&gt;
91                        &lt;/ul&gt;
92                    &lt;/div&gt;
93
94                &lt;/form&gt;
95            &lt;/div&gt;
96        &lt;/div&gt;
97    &lt;/div&gt;
98
99    &lt;script
100        src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js&quot;
101        integrity=&quot;sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p&quot;
102        crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
103    &lt;script type=&quot;text/javascript&quot; src=&quot;../javascript/script.js&quot;&gt;&lt;/script&gt;
104
105&lt;/body&gt;
106&lt;/html&gt;
107function readonlyForGivenMass() {
108  var x = document.getElementById(&quot;givenMass&quot;).readOnly;
109  
110}
111
112function readonlyForMolarMass() {
113  var x = document.getElementById(&quot;molarMass&quot;).readOnly;
114  
115}
116
117
118  
119    function readonlyForMoles() {
120      var x = document.getElementById(&quot;moles&quot;).readOnly;
121      
122
123}
124

Actually this is small part of java project. Hence I have used jsp and jstl. My file structure:

enter image description here

ANSWER

Answered 2022-Jan-27 at 06:58
1&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
2    pageEncoding=&quot;ISO-8859-1&quot;%&gt;
3&lt;!DOCTYPE html&gt;
4&lt;html&gt;
5&lt;head&gt;
6&lt;!-- Required meta tags --&gt;
7&lt;meta charset=&quot;utf-8&quot;&gt;
8&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
9
10&lt;!-- Bootstrap CSS --&gt;
11&lt;link
12    href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot;
13    rel=&quot;stylesheet&quot;
14    integrity=&quot;sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3&quot;
15    crossorigin=&quot;anonymous&quot;&gt;
16
17&lt;title&gt;Mole Calculator | Chemistry Calculator&lt;/title&gt;
18
19&lt;/head&gt;
20
21
22
23&lt;body&gt;
24
25    &lt;nav class=&quot;navbar fixed-top navbar-expand-lg navbar-dark bg-black&quot;&gt;
26
27        &lt;div class=&quot;container-fluid&quot;&gt;
28            &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;&lt;h4&gt;
29                    &lt;b&gt;Chemistry Calculator&lt;/b&gt;
30                &lt;/h4&gt;&lt;/a&gt;
31
32            &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot;
33                data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarSupportedContent&quot;
34                aria-controls=&quot;navbarSupportedContent&quot; aria-expanded=&quot;false&quot;
35                aria-label=&quot;Toggle navigation&quot;&gt;
36                &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
37            &lt;/button&gt;
38
39            &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarSupportedContent&quot;&gt;
40
41                &lt;ul class=&quot;navbar-nav  text-uppercase&quot;&gt;
42
43                    &lt;li class=&quot;nav-item&quot;&gt;&lt;a class=&quot;nav-link active&quot;
44                        aria-current=&quot;page&quot; href=&quot;/Chemistry-Calculator/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
45
46                    &lt;li class=&quot;nav-item&quot;&gt;&lt;a class=&quot;nav-link active&quot;
47                        aria-current=&quot;page&quot; href=&quot;/Chemistry-Calculator/about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;
48
49
50                &lt;/ul&gt;
51
52            &lt;/div&gt;
53        &lt;/div&gt;
54    &lt;/nav&gt;
55
56    &lt;div class=&quot;container&quot; style=&quot;padding-top: 5%;&quot;&gt;
57
58        &lt;div class=&quot;card px-4 py-5&quot; style=&quot;width: 650px;&quot;&gt;
59            &lt;div class=&quot;card-block&quot;&gt;
60
61                &lt;form action=&quot;/Chemistry-Calculator/Number-Of-Moles&quot;&gt;
62
63                    &lt;div class=&quot;mb-3&quot;&gt;
64                        &lt;label for=&quot;givenMass&quot; class=&quot;form-label&quot;&gt;Given Mass of
65                            Substance&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;givenMass&quot;
66                            aria-describedby=&quot;emailHelp&quot; name=&quot;givenMass&quot;
67                            value=&quot;${givenMass}&quot; style=&quot;width: 600px&quot;&gt;
68                    &lt;/div&gt;
69                    &lt;div class=&quot;mb-3&quot;&gt;
70                        &lt;label for=&quot;molarMass&quot; class=&quot;form-label&quot;&gt;Molar Mass&lt;/label&gt; &lt;input
71                            type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;molarMass&quot; name=&quot;molarMass&quot;
72                            value=&quot;${molarMass}&quot; style=&quot;width: 600px&quot;&gt;
73                    &lt;/div&gt;
74
75                    &lt;div class=&quot;mb-3&quot;&gt;
76                        &lt;label for=&quot;molarMass&quot; class=&quot;form-label&quot;&gt;Moles&lt;/label&gt; &lt;input
77                            type=&quot;text&quot;  class=&quot;form-control&quot;
78                            id=&quot;molarMass&quot; name=&quot;moles&quot; value=&quot;${moles}&quot; style=&quot;width: 600px&quot;&gt;
79                    &lt;/div&gt;
80
81                    &lt;input class=&quot;btn btn-outline-success&quot; type=&quot;submit&quot;
82                        value=&quot;Calculate&quot;&gt;
83                        
84                    &lt;div class=&quot;btn-group&quot;&gt;
85                        &lt;button type=&quot;button&quot; class=&quot;btn btn-success dropdown-toggle&quot;
86                            data-bs-toggle=&quot;dropdown&quot; aria-expanded=&quot;false&quot;&gt;Choose what to calculate &lt;/button&gt;
87                        &lt;ul class=&quot;dropdown-menu&quot;&gt;
88                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForMoles()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Moles&lt;/a&gt;&lt;/li&gt;
89                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForMolarMass()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Molar Mass&lt;/a&gt;&lt;/li&gt;
90                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForGivenMass()&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Given mass&lt;/a&gt;&lt;/li&gt;
91                        &lt;/ul&gt;
92                    &lt;/div&gt;
93
94                &lt;/form&gt;
95            &lt;/div&gt;
96        &lt;/div&gt;
97    &lt;/div&gt;
98
99    &lt;script
100        src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js&quot;
101        integrity=&quot;sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p&quot;
102        crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
103    &lt;script type=&quot;text/javascript&quot; src=&quot;../javascript/script.js&quot;&gt;&lt;/script&gt;
104
105&lt;/body&gt;
106&lt;/html&gt;
107function readonlyForGivenMass() {
108  var x = document.getElementById(&quot;givenMass&quot;).readOnly;
109  
110}
111
112function readonlyForMolarMass() {
113  var x = document.getElementById(&quot;molarMass&quot;).readOnly;
114  
115}
116
117
118  
119    function readonlyForMoles() {
120      var x = document.getElementById(&quot;moles&quot;).readOnly;
121      
122
123}
124&lt;!DOCTYPE html&gt;
125&lt;html&gt;
126&lt;head&gt;
127&lt;!-- Required meta tags --&gt;
128&lt;meta charset=&quot;utf-8&quot;&gt;
129&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
130
131&lt;!-- Bootstrap CSS --&gt;
132&lt;link
133    href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot;
134    rel=&quot;stylesheet&quot;
135    integrity=&quot;sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3&quot;
136    crossorigin=&quot;anonymous&quot;&gt;
137
138&lt;title&gt;Mole Calculator | Chemistry Calculator&lt;/title&gt;
139
140&lt;/head&gt;
141
142
143
144&lt;body&gt;
145
146    &lt;nav class=&quot;navbar fixed-top navbar-expand-lg navbar-dark bg-black&quot;&gt;
147
148        &lt;div class=&quot;container-fluid&quot;&gt;
149            &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;&lt;h4&gt;
150                    &lt;b&gt;Chemistry Calculator&lt;/b&gt;
151                &lt;/h4&gt;&lt;/a&gt;
152
153            &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot;
154                data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarSupportedContent&quot;
155                aria-controls=&quot;navbarSupportedContent&quot; aria-expanded=&quot;false&quot;
156                aria-label=&quot;Toggle navigation&quot;&gt;
157                &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
158            &lt;/button&gt;
159
160            &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarSupportedContent&quot;&gt;
161
162                &lt;ul class=&quot;navbar-nav  text-uppercase&quot;&gt;
163
164                    &lt;li class=&quot;nav-item&quot;&gt;&lt;a class=&quot;nav-link active&quot;
165                        aria-current=&quot;page&quot; href=&quot;/Chemistry-Calculator/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
166
167                    &lt;li class=&quot;nav-item&quot;&gt;&lt;a class=&quot;nav-link active&quot;
168                        aria-current=&quot;page&quot; href=&quot;/Chemistry-Calculator/about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;
169
170
171                &lt;/ul&gt;
172
173            &lt;/div&gt;
174        &lt;/div&gt;
175    &lt;/nav&gt;
176
177    &lt;div class=&quot;container&quot; style=&quot;padding-top: 5%;&quot;&gt;
178
179        &lt;div class=&quot;card px-4 py-5&quot; style=&quot;width: 650px;&quot;&gt;
180            &lt;div class=&quot;card-block&quot;&gt;
181
182                &lt;form action=&quot;/Chemistry-Calculator/Number-Of-Moles&quot;&gt;
183
184                    &lt;div class=&quot;mb-3&quot;&gt;
185                        &lt;label for=&quot;givenMass&quot; class=&quot;form-label&quot;&gt;Given Mass of
186                            Substance&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;givenMass&quot;
187                            aria-describedby=&quot;emailHelp&quot; name=&quot;givenMass&quot;
188                            value=&quot;${givenMass}&quot; style=&quot;width: 600px&quot;&gt;
189                    &lt;/div&gt;
190                    &lt;div class=&quot;mb-3&quot;&gt;
191                        &lt;label for=&quot;molarMass&quot; class=&quot;form-label&quot;&gt;Molar Mass&lt;/label&gt; &lt;input
192                            type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;moles&quot; name=&quot;molarMass&quot;
193                            value=&quot;${molarMass}&quot; style=&quot;width: 600px&quot;&gt;
194                    &lt;/div&gt;
195
196                    &lt;div class=&quot;mb-3&quot;&gt;
197                        &lt;label for=&quot;molarMass&quot; class=&quot;form-label&quot;&gt;Moles&lt;/label&gt; &lt;input
198                            type=&quot;text&quot;  class=&quot;form-control&quot;
199                            id=&quot;molarMass&quot; name=&quot;moles&quot; value=&quot;${moles}&quot; style=&quot;width: 600px&quot;&gt;
200                    &lt;/div&gt;
201
202                    &lt;input class=&quot;btn btn-outline-success&quot; type=&quot;submit&quot;
203                        value=&quot;Calculate&quot;&gt;
204                        
205                    &lt;div class=&quot;btn-group&quot;&gt;
206                        &lt;button type=&quot;button&quot; class=&quot;btn btn-success dropdown-toggle&quot;
207                            data-bs-toggle=&quot;dropdown&quot; aria-expanded=&quot;false&quot;&gt;Choose what to calculate &lt;/button&gt;
208                        &lt;ul class=&quot;dropdown-menu&quot;&gt;
209                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot;  onclick=&quot;readonlyForMoles(event)&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Moles&lt;/a&gt;&lt;/li&gt;
210                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForMolarMass(event)&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Molar Mass&lt;/a&gt;&lt;/li&gt;
211                            &lt;li&gt;&lt;a class=&quot;dropdown-item&quot; onclick=&quot;readonlyForGivenMass(event)&quot; href=&quot;/Chemistry-Calculator/Mole-Calculator&quot;&gt;Calculate Given mass&lt;/a&gt;&lt;/li&gt;
212                        &lt;/ul&gt;
213                    &lt;/div&gt;
214
215                &lt;/form&gt;
216            &lt;/div&gt;
217        &lt;/div&gt;
218    &lt;/div&gt;
219
220    &lt;script
221        src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js&quot;
222        integrity=&quot;sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p&quot;
223        crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
224
225        &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js&quot;&gt;&lt;/script&gt;
226    &lt;script&gt;
227            function readonlyForGivenMass(event) {
228                event.preventDefault()
229
230      var x = document.getElementById(&quot;moles&quot;).readOnly= false;
231  var x = document.getElementById(&quot;givenMass&quot;).readOnly= true;
232   var x = document.getElementById(&quot;molarMass&quot;).readOnly= false;
233  
234}
235
236function readonlyForMolarMass(event) {
237        event.preventDefault()
238  var x = document.getElementById(&quot;molarMass&quot;).readOnly = true;
239  var x = document.getElementById(&quot;moles&quot;).readOnly= false;
240  var x = document.getElementById(&quot;givenMass&quot;).readOnly= false;
241  
242}
243
244
245  
246    function readonlyForMoles(event) {
247        event.preventDefault()
248var x = document.getElementById(&quot;molarMass&quot;).readOnly = false;
249      var x = document.getElementById(&quot;moles&quot;).readOnly = true;
250      var x = document.getElementById(&quot;givenMass&quot;).readOnly= false;
251      
252
253}
254
255    &lt;/script&gt;
256
257&lt;/body&gt;
258&lt;/html&gt;
259

if you want means you can remove event.preventDefault in each function and I hope this code will works for you. Thank you

Source https://stackoverflow.com/questions/70810574

QUESTION

images not appear in the blade page if send it to email by using queue job Laravel?

Asked 2022-Jan-16 at 02:42

I send an email to user for verifying, by using queue job after registration, the job run successfully but the (blade page), which sent to the user doesn't show the images, Although if I sent the blade page without send it by queue job, the images appear fine!?

So the issue is that:

  • the images in the blade page in the user's email inbox, doesn't appear if I sent it by using the queue job, Although if I sent it directly without queue job, it appear fine.

image'URL if I sent it by using queue job:

http://localhost/assets/img/logo.png

enter image description here

image'URL if I sent it without using queue job:

http://localhost:8000/assets/img/logo.png

enter image description here

The Blade Page

1    &lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;
3    &lt;!-- Required meta tags --&gt;
4    &lt;meta charset=&quot;utf-8&quot;&gt;
5    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
6
7      &lt;link rel=&quot;stylesheet&quot; href=&quot;{{asset('assets/css/bootstrap.css')}}&quot;&gt;
8      &lt;style type=&quot;text/css&quot;&gt;
9      @import url({{asset('assets/css/style.css')}});
10
11      body {
12
13}
14      &lt;/style&gt;
15    &lt;title&gt;login Page&lt;/title&gt;
16  &lt;/head&gt;
17&lt;body&gt;
18&lt;section class=&quot;row&quot;&gt;
19    &lt;div class=&quot;col col-sm &quot;&gt;
20    &lt;/div&gt;
21  &lt;div class=&quot;col col-sm ml-5 pl-5&quot; id=&quot;col1&quot; &gt;
22    &lt;div class=&quot;container&quot;&gt;
23        &lt;div class=&quot;row mt-5 pl-5 mb-5 pb-5&quot;&gt;
24      &lt;img src=&quot;{{asset('assets/img/logo.png')}}&quot; width=&quot;80&quot; height=&quot;80&quot; alt=&quot;&quot;/&gt;
25        &lt;/div&gt;
26        &lt;div class=&quot;row mt-5 mb-5 pb-5 &quot;&gt;
27      &lt;img src=&quot;{{asset('assets/img/Sign in ~ Register Illustration.png')}}&quot; width=&quot;263&quot; height=&quot;241&quot; alt=&quot;&quot;/&gt;
28        &lt;/div&gt;
29        &lt;h1&gt;Hello,  &lt;/h1&gt;
30        &lt;h2&gt;Verification Code &lt;/h2&gt;
31        &lt;div class=&quot;row mt-5 mb-5 pb-5 pr-5&quot;&gt;
32        &lt;p class=&quot;font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted&quot; id=&quot;text1&quot;&gt;1Me will Keep your Contacts Secured in our Data base&lt;/p&gt;
33        &lt;/div&gt;
34
35      &lt;/div&gt;
36
37  &lt;/div&gt;
38    &lt;/section&gt;
39&lt;script src=&quot;{{asset('js/bootstrap.js')}}&quot;&gt;&lt;/script&gt;
40
41&lt;/body&gt;
42&lt;/html&gt;
43

Route:

1    &lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;
3    &lt;!-- Required meta tags --&gt;
4    &lt;meta charset=&quot;utf-8&quot;&gt;
5    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
6
7      &lt;link rel=&quot;stylesheet&quot; href=&quot;{{asset('assets/css/bootstrap.css')}}&quot;&gt;
8      &lt;style type=&quot;text/css&quot;&gt;
9      @import url({{asset('assets/css/style.css')}});
10
11      body {
12
13}
14      &lt;/style&gt;
15    &lt;title&gt;login Page&lt;/title&gt;
16  &lt;/head&gt;
17&lt;body&gt;
18&lt;section class=&quot;row&quot;&gt;
19    &lt;div class=&quot;col col-sm &quot;&gt;
20    &lt;/div&gt;
21  &lt;div class=&quot;col col-sm ml-5 pl-5&quot; id=&quot;col1&quot; &gt;
22    &lt;div class=&quot;container&quot;&gt;
23        &lt;div class=&quot;row mt-5 pl-5 mb-5 pb-5&quot;&gt;
24      &lt;img src=&quot;{{asset('assets/img/logo.png')}}&quot; width=&quot;80&quot; height=&quot;80&quot; alt=&quot;&quot;/&gt;
25        &lt;/div&gt;
26        &lt;div class=&quot;row mt-5 mb-5 pb-5 &quot;&gt;
27      &lt;img src=&quot;{{asset('assets/img/Sign in ~ Register Illustration.png')}}&quot; width=&quot;263&quot; height=&quot;241&quot; alt=&quot;&quot;/&gt;
28        &lt;/div&gt;
29        &lt;h1&gt;Hello,  &lt;/h1&gt;
30        &lt;h2&gt;Verification Code &lt;/h2&gt;
31        &lt;div class=&quot;row mt-5 mb-5 pb-5 pr-5&quot;&gt;
32        &lt;p class=&quot;font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted&quot; id=&quot;text1&quot;&gt;1Me will Keep your Contacts Secured in our Data base&lt;/p&gt;
33        &lt;/div&gt;
34
35      &lt;/div&gt;
36
37  &lt;/div&gt;
38    &lt;/section&gt;
39&lt;script src=&quot;{{asset('js/bootstrap.js')}}&quot;&gt;&lt;/script&gt;
40
41&lt;/body&gt;
42&lt;/html&gt;
43    Route::group(['middleware'=&gt;'guest:web'], function(){
44    Route::get('/register', [registerController::class,'register'])-&gt;name('site.register');
45    Route::match(['get','post'],'/register-create', [registerController::class,'create'])-&gt;name('site.register.create');
46});
47

Controller:

1    &lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;
3    &lt;!-- Required meta tags --&gt;
4    &lt;meta charset=&quot;utf-8&quot;&gt;
5    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
6
7      &lt;link rel=&quot;stylesheet&quot; href=&quot;{{asset('assets/css/bootstrap.css')}}&quot;&gt;
8      &lt;style type=&quot;text/css&quot;&gt;
9      @import url({{asset('assets/css/style.css')}});
10
11      body {
12
13}
14      &lt;/style&gt;
15    &lt;title&gt;login Page&lt;/title&gt;
16  &lt;/head&gt;
17&lt;body&gt;
18&lt;section class=&quot;row&quot;&gt;
19    &lt;div class=&quot;col col-sm &quot;&gt;
20    &lt;/div&gt;
21  &lt;div class=&quot;col col-sm ml-5 pl-5&quot; id=&quot;col1&quot; &gt;
22    &lt;div class=&quot;container&quot;&gt;
23        &lt;div class=&quot;row mt-5 pl-5 mb-5 pb-5&quot;&gt;
24      &lt;img src=&quot;{{asset('assets/img/logo.png')}}&quot; width=&quot;80&quot; height=&quot;80&quot; alt=&quot;&quot;/&gt;
25        &lt;/div&gt;
26        &lt;div class=&quot;row mt-5 mb-5 pb-5 &quot;&gt;
27      &lt;img src=&quot;{{asset('assets/img/Sign in ~ Register Illustration.png')}}&quot; width=&quot;263&quot; height=&quot;241&quot; alt=&quot;&quot;/&gt;
28        &lt;/div&gt;
29        &lt;h1&gt;Hello,  &lt;/h1&gt;
30        &lt;h2&gt;Verification Code &lt;/h2&gt;
31        &lt;div class=&quot;row mt-5 mb-5 pb-5 pr-5&quot;&gt;
32        &lt;p class=&quot;font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted&quot; id=&quot;text1&quot;&gt;1Me will Keep your Contacts Secured in our Data base&lt;/p&gt;
33        &lt;/div&gt;
34
35      &lt;/div&gt;
36
37  &lt;/div&gt;
38    &lt;/section&gt;
39&lt;script src=&quot;{{asset('js/bootstrap.js')}}&quot;&gt;&lt;/script&gt;
40
41&lt;/body&gt;
42&lt;/html&gt;
43    Route::group(['middleware'=&gt;'guest:web'], function(){
44    Route::get('/register', [registerController::class,'register'])-&gt;name('site.register');
45    Route::match(['get','post'],'/register-create', [registerController::class,'create'])-&gt;name('site.register.create');
46});
47    public function create(RegisterRequest $request)
48{
49     $user = User::create([
50        'firstName' =&gt; $request-&gt;firstName,
51        'middleName' =&gt; $request-&gt;middleName,
52        'lastName' =&gt; $request-&gt;lastName,
53        'email' =&gt; $request-&gt;email,
54        'password' =&gt; Hash::make($request-&gt;password),
55    ]);
56    $on = \Carbon\Carbon::now()-&gt;addSecond(10);
57     dispatch(new VerifyEmailJob($user))-&gt;delay($on);
58    return redirect()-&gt;route('landingPage')-&gt;with(['success'=&gt;'We sent verifying email check it']);
59}
60

queue job:

1    &lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;
3    &lt;!-- Required meta tags --&gt;
4    &lt;meta charset=&quot;utf-8&quot;&gt;
5    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
6
7      &lt;link rel=&quot;stylesheet&quot; href=&quot;{{asset('assets/css/bootstrap.css')}}&quot;&gt;
8      &lt;style type=&quot;text/css&quot;&gt;
9      @import url({{asset('assets/css/style.css')}});
10
11      body {
12
13}
14      &lt;/style&gt;
15    &lt;title&gt;login Page&lt;/title&gt;
16  &lt;/head&gt;
17&lt;body&gt;
18&lt;section class=&quot;row&quot;&gt;
19    &lt;div class=&quot;col col-sm &quot;&gt;
20    &lt;/div&gt;
21  &lt;div class=&quot;col col-sm ml-5 pl-5&quot; id=&quot;col1&quot; &gt;
22    &lt;div class=&quot;container&quot;&gt;
23        &lt;div class=&quot;row mt-5 pl-5 mb-5 pb-5&quot;&gt;
24      &lt;img src=&quot;{{asset('assets/img/logo.png')}}&quot; width=&quot;80&quot; height=&quot;80&quot; alt=&quot;&quot;/&gt;
25        &lt;/div&gt;
26        &lt;div class=&quot;row mt-5 mb-5 pb-5 &quot;&gt;
27      &lt;img src=&quot;{{asset('assets/img/Sign in ~ Register Illustration.png')}}&quot; width=&quot;263&quot; height=&quot;241&quot; alt=&quot;&quot;/&gt;
28        &lt;/div&gt;
29        &lt;h1&gt;Hello,  &lt;/h1&gt;
30        &lt;h2&gt;Verification Code &lt;/h2&gt;
31        &lt;div class=&quot;row mt-5 mb-5 pb-5 pr-5&quot;&gt;
32        &lt;p class=&quot;font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted&quot; id=&quot;text1&quot;&gt;1Me will Keep your Contacts Secured in our Data base&lt;/p&gt;
33        &lt;/div&gt;
34
35      &lt;/div&gt;
36
37  &lt;/div&gt;
38    &lt;/section&gt;
39&lt;script src=&quot;{{asset('js/bootstrap.js')}}&quot;&gt;&lt;/script&gt;
40
41&lt;/body&gt;
42&lt;/html&gt;
43    Route::group(['middleware'=&gt;'guest:web'], function(){
44    Route::get('/register', [registerController::class,'register'])-&gt;name('site.register');
45    Route::match(['get','post'],'/register-create', [registerController::class,'create'])-&gt;name('site.register.create');
46});
47    public function create(RegisterRequest $request)
48{
49     $user = User::create([
50        'firstName' =&gt; $request-&gt;firstName,
51        'middleName' =&gt; $request-&gt;middleName,
52        'lastName' =&gt; $request-&gt;lastName,
53        'email' =&gt; $request-&gt;email,
54        'password' =&gt; Hash::make($request-&gt;password),
55    ]);
56    $on = \Carbon\Carbon::now()-&gt;addSecond(10);
57     dispatch(new VerifyEmailJob($user))-&gt;delay($on);
58    return redirect()-&gt;route('landingPage')-&gt;with(['success'=&gt;'We sent verifying email check it']);
59}
60    &lt;?php
61
62namespace App\Jobs;
63
64use App\Mail\VerifyEmail;
65use Illuminate\Bus\Queueable;
66use Illuminate\Contracts\Queue\ShouldQueue;
67use Illuminate\Foundation\Bus\Dispatchable;
68use Illuminate\Queue\InteractsWithQueue;
69use Illuminate\Queue\SerializesModels;
70use Illuminate\Support\Facades\Mail;
71
72class VerifyEmailJob implements ShouldQueue
73{
74    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
75
76    /**
77     * Create a new job instance.
78     *
79     * @return void
80     */
81    public $user;
82    public function __construct($user)
83    {
84        $this-&gt;user= $user;
85    }
86
87    /**
88     * Execute the job.
89     *
90     * @return void
91     */
92    public function handle()
93    {
94        Mail::to($this-&gt;user-&gt;email)-&gt;send(new VerifyEmail($this-&gt;user));
95
96    }
97}
98

Mail class:

1    &lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;
3    &lt;!-- Required meta tags --&gt;
4    &lt;meta charset=&quot;utf-8&quot;&gt;
5    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
6
7      &lt;link rel=&quot;stylesheet&quot; href=&quot;{{asset('assets/css/bootstrap.css')}}&quot;&gt;
8      &lt;style type=&quot;text/css&quot;&gt;
9      @import url({{asset('assets/css/style.css')}});
10
11      body {
12
13}
14      &lt;/style&gt;
15    &lt;title&gt;login Page&lt;/title&gt;
16  &lt;/head&gt;
17&lt;body&gt;
18&lt;section class=&quot;row&quot;&gt;
19    &lt;div class=&quot;col col-sm &quot;&gt;
20    &lt;/div&gt;
21  &lt;div class=&quot;col col-sm ml-5 pl-5&quot; id=&quot;col1&quot; &gt;
22    &lt;div class=&quot;container&quot;&gt;
23        &lt;div class=&quot;row mt-5 pl-5 mb-5 pb-5&quot;&gt;
24      &lt;img src=&quot;{{asset('assets/img/logo.png')}}&quot; width=&quot;80&quot; height=&quot;80&quot; alt=&quot;&quot;/&gt;
25        &lt;/div&gt;
26        &lt;div class=&quot;row mt-5 mb-5 pb-5 &quot;&gt;
27      &lt;img src=&quot;{{asset('assets/img/Sign in ~ Register Illustration.png')}}&quot; width=&quot;263&quot; height=&quot;241&quot; alt=&quot;&quot;/&gt;
28        &lt;/div&gt;
29        &lt;h1&gt;Hello,  &lt;/h1&gt;
30        &lt;h2&gt;Verification Code &lt;/h2&gt;
31        &lt;div class=&quot;row mt-5 mb-5 pb-5 pr-5&quot;&gt;
32        &lt;p class=&quot;font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted&quot; id=&quot;text1&quot;&gt;1Me will Keep your Contacts Secured in our Data base&lt;/p&gt;
33        &lt;/div&gt;
34
35      &lt;/div&gt;
36
37  &lt;/div&gt;
38    &lt;/section&gt;
39&lt;script src=&quot;{{asset('js/bootstrap.js')}}&quot;&gt;&lt;/script&gt;
40
41&lt;/body&gt;
42&lt;/html&gt;
43    Route::group(['middleware'=&gt;'guest:web'], function(){
44    Route::get('/register', [registerController::class,'register'])-&gt;name('site.register');
45    Route::match(['get','post'],'/register-create', [registerController::class,'create'])-&gt;name('site.register.create');
46});
47    public function create(RegisterRequest $request)
48{
49     $user = User::create([
50        'firstName' =&gt; $request-&gt;firstName,
51        'middleName' =&gt; $request-&gt;middleName,
52        'lastName' =&gt; $request-&gt;lastName,
53        'email' =&gt; $request-&gt;email,
54        'password' =&gt; Hash::make($request-&gt;password),
55    ]);
56    $on = \Carbon\Carbon::now()-&gt;addSecond(10);
57     dispatch(new VerifyEmailJob($user))-&gt;delay($on);
58    return redirect()-&gt;route('landingPage')-&gt;with(['success'=&gt;'We sent verifying email check it']);
59}
60    &lt;?php
61
62namespace App\Jobs;
63
64use App\Mail\VerifyEmail;
65use Illuminate\Bus\Queueable;
66use Illuminate\Contracts\Queue\ShouldQueue;
67use Illuminate\Foundation\Bus\Dispatchable;
68use Illuminate\Queue\InteractsWithQueue;
69use Illuminate\Queue\SerializesModels;
70use Illuminate\Support\Facades\Mail;
71
72class VerifyEmailJob implements ShouldQueue
73{
74    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
75
76    /**
77     * Create a new job instance.
78     *
79     * @return void
80     */
81    public $user;
82    public function __construct($user)
83    {
84        $this-&gt;user= $user;
85    }
86
87    /**
88     * Execute the job.
89     *
90     * @return void
91     */
92    public function handle()
93    {
94        Mail::to($this-&gt;user-&gt;email)-&gt;send(new VerifyEmail($this-&gt;user));
95
96    }
97}
98    &lt;?php
99
100namespace App\Mail;
101
102use Illuminate\Bus\Queueable;
103use Illuminate\Mail\Mailable;
104use Illuminate\Queue\SerializesModels;
105
106class VerifyEmail extends Mailable
107{
108    use Queueable, SerializesModels;
109
110    /**
111     * Create a new message instance.
112     *
113     * @return void
114     */
115    public $user;
116
117    public function __construct($user)
118    {
119        $this-&gt;user = $user;
120    }
121    /**
122     * Build the message.
123     *
124     * @return $this
125     */
126    public function build()
127    {
128        $user = $this-&gt;user;
129        return $this-&gt;subject('Mail from Oneme')
130            -&gt;view('site.auth.verifyEmail',compact('user'));
131    }
132}
133

Any Help

ANSWER

Answered 2022-Jan-16 at 02:42

I have faced this issue before. For emails all path must be a Fully Qualified URL. Because queue jobs can not smartly figure out what the application's base url should be.

https://example.com/static/logo.png is a Fully Qualified URL, but /static/logo.png isn't. For this, I use a APP_URL env key.

When a action is being performed without http request(Like in queue system), laravel can not translate /static/logo.png to https://example.com/static/logo.png

On .env file I'd do something like

1    &lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;
3    &lt;!-- Required meta tags --&gt;
4    &lt;meta charset=&quot;utf-8&quot;&gt;
5    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
6
7      &lt;link rel=&quot;stylesheet&quot; href=&quot;{{asset('assets/css/bootstrap.css')}}&quot;&gt;
8      &lt;style type=&quot;text/css&quot;&gt;
9      @import url({{asset('assets/css/style.css')}});
10
11      body {
12
13}
14      &lt;/style&gt;
15    &lt;title&gt;login Page&lt;/title&gt;
16  &lt;/head&gt;
17&lt;body&gt;
18&lt;section class=&quot;row&quot;&gt;
19    &lt;div class=&quot;col col-sm &quot;&gt;
20    &lt;/div&gt;
21  &lt;div class=&quot;col col-sm ml-5 pl-5&quot; id=&quot;col1&quot; &gt;
22    &lt;div class=&quot;container&quot;&gt;
23        &lt;div class=&quot;row mt-5 pl-5 mb-5 pb-5&quot;&gt;
24      &lt;img src=&quot;{{asset('assets/img/logo.png')}}&quot; width=&quot;80&quot; height=&quot;80&quot; alt=&quot;&quot;/&gt;
25        &lt;/div&gt;
26        &lt;div class=&quot;row mt-5 mb-5 pb-5 &quot;&gt;
27      &lt;img src=&quot;{{asset('assets/img/Sign in ~ Register Illustration.png')}}&quot; width=&quot;263&quot; height=&quot;241&quot; alt=&quot;&quot;/&gt;
28        &lt;/div&gt;
29        &lt;h1&gt;Hello,  &lt;/h1&gt;
30        &lt;h2&gt;Verification Code &lt;/h2&gt;
31        &lt;div class=&quot;row mt-5 mb-5 pb-5 pr-5&quot;&gt;
32        &lt;p class=&quot;font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted&quot; id=&quot;text1&quot;&gt;1Me will Keep your Contacts Secured in our Data base&lt;/p&gt;
33        &lt;/div&gt;
34
35      &lt;/div&gt;
36
37  &lt;/div&gt;
38    &lt;/section&gt;
39&lt;script src=&quot;{{asset('js/bootstrap.js')}}&quot;&gt;&lt;/script&gt;
40
41&lt;/body&gt;
42&lt;/html&gt;
43    Route::group(['middleware'=&gt;'guest:web'], function(){
44    Route::get('/register', [registerController::class,'register'])-&gt;name('site.register');
45    Route::match(['get','post'],'/register-create', [registerController::class,'create'])-&gt;name('site.register.create');
46});
47    public function create(RegisterRequest $request)
48{
49     $user = User::create([
50        'firstName' =&gt; $request-&gt;firstName,
51        'middleName' =&gt; $request-&gt;middleName,
52        'lastName' =&gt; $request-&gt;lastName,
53        'email' =&gt; $request-&gt;email,
54        'password' =&gt; Hash::make($request-&gt;password),
55    ]);
56    $on = \Carbon\Carbon::now()-&gt;addSecond(10);
57     dispatch(new VerifyEmailJob($user))-&gt;delay($on);
58    return redirect()-&gt;route('landingPage')-&gt;with(['success'=&gt;'We sent verifying email check it']);
59}
60    &lt;?php
61
62namespace App\Jobs;
63
64use App\Mail\VerifyEmail;
65use Illuminate\Bus\Queueable;
66use Illuminate\Contracts\Queue\ShouldQueue;
67use Illuminate\Foundation\Bus\Dispatchable;
68use Illuminate\Queue\InteractsWithQueue;
69use Illuminate\Queue\SerializesModels;
70use Illuminate\Support\Facades\Mail;
71
72class VerifyEmailJob implements ShouldQueue
73{
74    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
75
76    /**
77     * Create a new job instance.
78     *
79     * @return void
80     */
81    public $user;
82    public function __construct($user)
83    {
84        $this-&gt;user= $user;
85    }
86
87    /**
88     * Execute the job.
89     *
90     * @return void
91     */
92    public function handle()
93    {
94        Mail::to($this-&gt;user-&gt;email)-&gt;send(new VerifyEmail($this-&gt;user));
95
96    }
97}
98    &lt;?php
99
100namespace App\Mail;
101
102use Illuminate\Bus\Queueable;
103use Illuminate\Mail\Mailable;
104use Illuminate\Queue\SerializesModels;
105
106class VerifyEmail extends Mailable
107{
108    use Queueable, SerializesModels;
109
110    /**
111     * Create a new message instance.
112     *
113     * @return void
114     */
115    public $user;
116
117    public function __construct($user)
118    {
119        $this-&gt;user = $user;
120    }
121    /**
122     * Build the message.
123     *
124     * @return $this
125     */
126    public function build()
127    {
128        $user = $this-&gt;user;
129        return $this-&gt;subject('Mail from Oneme')
130            -&gt;view('site.auth.verifyEmail',compact('user'));
131    }
132}
133APP_URL = &quot;https://example.com&quot;    #change this with your application url
134

The on the view file, I'd do something like

1    &lt;!doctype html&gt;
2&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;
3    &lt;!-- Required meta tags --&gt;
4    &lt;meta charset=&quot;utf-8&quot;&gt;
5    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
6
7      &lt;link rel=&quot;stylesheet&quot; href=&quot;{{asset('assets/css/bootstrap.css')}}&quot;&gt;
8      &lt;style type=&quot;text/css&quot;&gt;
9      @import url({{asset('assets/css/style.css')}});
10
11      body {
12
13}
14      &lt;/style&gt;
15    &lt;title&gt;login Page&lt;/title&gt;
16  &lt;/head&gt;
17&lt;body&gt;
18&lt;section class=&quot;row&quot;&gt;
19    &lt;div class=&quot;col col-sm &quot;&gt;
20    &lt;/div&gt;
21  &lt;div class=&quot;col col-sm ml-5 pl-5&quot; id=&quot;col1&quot; &gt;
22    &lt;div class=&quot;container&quot;&gt;
23        &lt;div class=&quot;row mt-5 pl-5 mb-5 pb-5&quot;&gt;
24      &lt;img src=&quot;{{asset('assets/img/logo.png')}}&quot; width=&quot;80&quot; height=&quot;80&quot; alt=&quot;&quot;/&gt;
25        &lt;/div&gt;
26        &lt;div class=&quot;row mt-5 mb-5 pb-5 &quot;&gt;
27      &lt;img src=&quot;{{asset('assets/img/Sign in ~ Register Illustration.png')}}&quot; width=&quot;263&quot; height=&quot;241&quot; alt=&quot;&quot;/&gt;
28        &lt;/div&gt;
29        &lt;h1&gt;Hello,  &lt;/h1&gt;
30        &lt;h2&gt;Verification Code &lt;/h2&gt;
31        &lt;div class=&quot;row mt-5 mb-5 pb-5 pr-5&quot;&gt;
32        &lt;p class=&quot;font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted&quot; id=&quot;text1&quot;&gt;1Me will Keep your Contacts Secured in our Data base&lt;/p&gt;
33        &lt;/div&gt;
34
35      &lt;/div&gt;
36
37  &lt;/div&gt;
38    &lt;/section&gt;
39&lt;script src=&quot;{{asset('js/bootstrap.js')}}&quot;&gt;&lt;/script&gt;
40
41&lt;/body&gt;
42&lt;/html&gt;
43    Route::group(['middleware'=&gt;'guest:web'], function(){
44    Route::get('/register', [registerController::class,'register'])-&gt;name('site.register');
45    Route::match(['get','post'],'/register-create', [registerController::class,'create'])-&gt;name('site.register.create');
46});
47    public function create(RegisterRequest $request)
48{
49     $user = User::create([
50        'firstName' =&gt; $request-&gt;firstName,
51        'middleName' =&gt; $request-&gt;middleName,
52        'lastName' =&gt; $request-&gt;lastName,
53        'email' =&gt; $request-&gt;email,
54        'password' =&gt; Hash::make($request-&gt;password),
55    ]);
56    $on = \Carbon\Carbon::now()-&gt;addSecond(10);
57     dispatch(new VerifyEmailJob($user))-&gt;delay($on);
58    return redirect()-&gt;route('landingPage')-&gt;with(['success'=&gt;'We sent verifying email check it']);
59}
60    &lt;?php
61
62namespace App\Jobs;
63
64use App\Mail\VerifyEmail;
65use Illuminate\Bus\Queueable;
66use Illuminate\Contracts\Queue\ShouldQueue;
67use Illuminate\Foundation\Bus\Dispatchable;
68use Illuminate\Queue\InteractsWithQueue;
69use Illuminate\Queue\SerializesModels;
70use Illuminate\Support\Facades\Mail;
71
72class VerifyEmailJob implements ShouldQueue
73{
74    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
75
76    /**
77     * Create a new job instance.
78     *
79     * @return void
80     */
81    public $user;
82    public function __construct($user)
83    {
84        $this-&gt;user= $user;
85    }
86
87    /**
88     * Execute the job.
89     *
90     * @return void
91     */
92    public function handle()
93    {
94        Mail::to($this-&gt;user-&gt;email)-&gt;send(new VerifyEmail($this-&gt;user));
95
96    }
97}
98    &lt;?php
99
100namespace App\Mail;
101
102use Illuminate\Bus\Queueable;
103use Illuminate\Mail\Mailable;
104use Illuminate\Queue\SerializesModels;
105
106class VerifyEmail extends Mailable
107{
108    use Queueable, SerializesModels;
109
110    /**
111     * Create a new message instance.
112     *
113     * @return void
114     */
115    public $user;
116
117    public function __construct($user)
118    {
119        $this-&gt;user = $user;
120    }
121    /**
122     * Build the message.
123     *
124     * @return $this
125     */
126    public function build()
127    {
128        $user = $this-&gt;user;
129        return $this-&gt;subject('Mail from Oneme')
130            -&gt;view('site.auth.verifyEmail',compact('user'));
131    }
132}
133APP_URL = &quot;https://example.com&quot;    #change this with your application url
134&lt;img src={{ env('APP_URL') . '/static/logo.png' }} /&gt;
135

Source https://stackoverflow.com/questions/70721643

QUESTION

FirebaseOptions cannot be null when creating the default app

Asked 2021-Dec-25 at 09:13

I am trying to try a sample project in Flutter integration email and google based login, and planning to use firebase initialisation for doing it while I have followed all the steps as mentioned in tutorials I am getting this error as soon as firebase is attempted to be initialised.

1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16

Here is my index.html

1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16&lt;!DOCTYPE html&gt;
17&lt;html&gt;
18&lt;head&gt;
19  &lt;!--
20    If you are serving your web app in a path other than the root, change the
21    href value below to reflect the base path you are serving from.
22
23    The path provided below has to start and end with a slash &quot;/&quot; in order for
24    it to work correctly.
25
26    For more details:
27    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
28
29    This is a placeholder for base href that will be replaced by the value of
30    the `--base-href` argument provided to `flutter build`.
31  --&gt;
32  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
33
34  &lt;meta charset=&quot;UTF-8&quot;&gt;
35  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
36  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
37  &lt;meta name=&quot;google-signin-client_id&quot; content=&quot;619218114547-xxxx.apps.googleusercontent.com&quot;&gt;
38  &lt;!-- iOS meta tags &amp; icons --&gt;
39  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
40  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
41  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;signin_example&quot;&gt;
42  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
43  
44  &lt;!-- Favicon --&gt;
45  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
46
47  &lt;title&gt;signin_example&lt;/title&gt;
48  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
49&lt;/head&gt;
50&lt;body&gt;
51  &lt;!-- This script installs service_worker.js to provide PWA functionality to
52       application. For more information, see:
53       https://developers.google.com/web/fundamentals/primers/service-workers --&gt;
54  
55  
56  &lt;script&gt;
57    var serviceWorkerVersion = null;
58    var scriptLoaded = false;
59    function loadMainDartJs() {
60      if (scriptLoaded) {
61        return;
62      }
63      scriptLoaded = true;
64      var scriptTag = document.createElement('script');
65      scriptTag.src = 'main.dart.js';
66      scriptTag.type = 'application/javascript';
67      document.body.append(scriptTag);
68    }
69
70    if ('serviceWorker' in navigator) {
71      // Service workers are supported. Use them.
72      window.addEventListener('load', function () {
73        // Wait for registration to finish before dropping the &lt;script&gt; tag.
74        // Otherwise, the browser will load the script multiple times,
75        // potentially different versions.
76        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
77        navigator.serviceWorker.register(serviceWorkerUrl)
78          .then((reg) =&gt; {
79            function waitForActivation(serviceWorker) {
80              serviceWorker.addEventListener('statechange', () =&gt; {
81                if (serviceWorker.state == 'activated') {
82                  console.log('Installed new service worker.');
83                  loadMainDartJs();
84                }
85              });
86            }
87            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
88              // No active web worker and we have installed or are installing
89              // one for the first time. Simply wait for it to activate.
90              waitForActivation(reg.installing || reg.waiting);
91            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
92              // When the app updates the serviceWorkerVersion changes, so we
93              // need to ask the service worker to update.
94              console.log('New service worker available.');
95              reg.update();
96              waitForActivation(reg.installing);
97            } else {
98              // Existing service worker is still good.
99              console.log('Loading app from service worker.');
100              loadMainDartJs();
101            }
102          });
103
104        // If service worker doesn't succeed in a reasonable amount of time,
105        // fallback to plaint &lt;script&gt; tag.
106        setTimeout(() =&gt; {
107          if (!scriptLoaded) {
108            console.warn(
109              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
110            );
111            loadMainDartJs();
112          }
113        }, 4000);
114      });
115    } else {
116      // Service workers not supported. Just drop the &lt;script&gt; tag.
117      loadMainDartJs();
118    }
119  &lt;/script&gt;
120  &lt;script type=&quot;module&quot;&gt;
121    // Import the functions you need from the SDKs you need
122    import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js&quot;;
123    import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js&quot;;
124    // TODO: Add SDKs for Firebase products that you want to use
125    // https://firebase.google.com/docs/web/setup#available-libraries
126
127    // Your web app's Firebase configuration
128    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
129    const firebaseConfig = {
130      apiKey: &quot;xxx&quot;,
131      authDomain: &quot;xxx&quot;,
132      projectId: &quot;xx&quot;,
133      storageBucket: &quot;exxx&quot;,
134      messagingSenderId: &quot;xxx&quot;,
135      appId: &quot;xxx&quot;,
136      measurementId: &quot;xxx&quot;
137    };
138
139    // Initialize Firebase
140    const app = initializeApp(firebaseConfig);
141    const analytics = getAnalytics(app);
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145

Part of code from main.dart file where firebase initialisation is happening

1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16&lt;!DOCTYPE html&gt;
17&lt;html&gt;
18&lt;head&gt;
19  &lt;!--
20    If you are serving your web app in a path other than the root, change the
21    href value below to reflect the base path you are serving from.
22
23    The path provided below has to start and end with a slash &quot;/&quot; in order for
24    it to work correctly.
25
26    For more details:
27    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
28
29    This is a placeholder for base href that will be replaced by the value of
30    the `--base-href` argument provided to `flutter build`.
31  --&gt;
32  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
33
34  &lt;meta charset=&quot;UTF-8&quot;&gt;
35  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
36  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
37  &lt;meta name=&quot;google-signin-client_id&quot; content=&quot;619218114547-xxxx.apps.googleusercontent.com&quot;&gt;
38  &lt;!-- iOS meta tags &amp; icons --&gt;
39  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
40  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
41  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;signin_example&quot;&gt;
42  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
43  
44  &lt;!-- Favicon --&gt;
45  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
46
47  &lt;title&gt;signin_example&lt;/title&gt;
48  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
49&lt;/head&gt;
50&lt;body&gt;
51  &lt;!-- This script installs service_worker.js to provide PWA functionality to
52       application. For more information, see:
53       https://developers.google.com/web/fundamentals/primers/service-workers --&gt;
54  
55  
56  &lt;script&gt;
57    var serviceWorkerVersion = null;
58    var scriptLoaded = false;
59    function loadMainDartJs() {
60      if (scriptLoaded) {
61        return;
62      }
63      scriptLoaded = true;
64      var scriptTag = document.createElement('script');
65      scriptTag.src = 'main.dart.js';
66      scriptTag.type = 'application/javascript';
67      document.body.append(scriptTag);
68    }
69
70    if ('serviceWorker' in navigator) {
71      // Service workers are supported. Use them.
72      window.addEventListener('load', function () {
73        // Wait for registration to finish before dropping the &lt;script&gt; tag.
74        // Otherwise, the browser will load the script multiple times,
75        // potentially different versions.
76        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
77        navigator.serviceWorker.register(serviceWorkerUrl)
78          .then((reg) =&gt; {
79            function waitForActivation(serviceWorker) {
80              serviceWorker.addEventListener('statechange', () =&gt; {
81                if (serviceWorker.state == 'activated') {
82                  console.log('Installed new service worker.');
83                  loadMainDartJs();
84                }
85              });
86            }
87            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
88              // No active web worker and we have installed or are installing
89              // one for the first time. Simply wait for it to activate.
90              waitForActivation(reg.installing || reg.waiting);
91            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
92              // When the app updates the serviceWorkerVersion changes, so we
93              // need to ask the service worker to update.
94              console.log('New service worker available.');
95              reg.update();
96              waitForActivation(reg.installing);
97            } else {
98              // Existing service worker is still good.
99              console.log('Loading app from service worker.');
100              loadMainDartJs();
101            }
102          });
103
104        // If service worker doesn't succeed in a reasonable amount of time,
105        // fallback to plaint &lt;script&gt; tag.
106        setTimeout(() =&gt; {
107          if (!scriptLoaded) {
108            console.warn(
109              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
110            );
111            loadMainDartJs();
112          }
113        }, 4000);
114      });
115    } else {
116      // Service workers not supported. Just drop the &lt;script&gt; tag.
117      loadMainDartJs();
118    }
119  &lt;/script&gt;
120  &lt;script type=&quot;module&quot;&gt;
121    // Import the functions you need from the SDKs you need
122    import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js&quot;;
123    import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js&quot;;
124    // TODO: Add SDKs for Firebase products that you want to use
125    // https://firebase.google.com/docs/web/setup#available-libraries
126
127    // Your web app's Firebase configuration
128    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
129    const firebaseConfig = {
130      apiKey: &quot;xxx&quot;,
131      authDomain: &quot;xxx&quot;,
132      projectId: &quot;xx&quot;,
133      storageBucket: &quot;exxx&quot;,
134      messagingSenderId: &quot;xxx&quot;,
135      appId: &quot;xxx&quot;,
136      measurementId: &quot;xxx&quot;
137    };
138
139    // Initialize Firebase
140    const app = initializeApp(firebaseConfig);
141    const analytics = getAnalytics(app);
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145void main() async {
146  WidgetsFlutterBinding.ensureInitialized();
147  await Firebase.initializeApp();
148  runApp(SignUpApp());
149}
150

Pubsec.yaml file of the project

1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16&lt;!DOCTYPE html&gt;
17&lt;html&gt;
18&lt;head&gt;
19  &lt;!--
20    If you are serving your web app in a path other than the root, change the
21    href value below to reflect the base path you are serving from.
22
23    The path provided below has to start and end with a slash &quot;/&quot; in order for
24    it to work correctly.
25
26    For more details:
27    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
28
29    This is a placeholder for base href that will be replaced by the value of
30    the `--base-href` argument provided to `flutter build`.
31  --&gt;
32  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
33
34  &lt;meta charset=&quot;UTF-8&quot;&gt;
35  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
36  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
37  &lt;meta name=&quot;google-signin-client_id&quot; content=&quot;619218114547-xxxx.apps.googleusercontent.com&quot;&gt;
38  &lt;!-- iOS meta tags &amp; icons --&gt;
39  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
40  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
41  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;signin_example&quot;&gt;
42  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
43  
44  &lt;!-- Favicon --&gt;
45  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
46
47  &lt;title&gt;signin_example&lt;/title&gt;
48  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
49&lt;/head&gt;
50&lt;body&gt;
51  &lt;!-- This script installs service_worker.js to provide PWA functionality to
52       application. For more information, see:
53       https://developers.google.com/web/fundamentals/primers/service-workers --&gt;
54  
55  
56  &lt;script&gt;
57    var serviceWorkerVersion = null;
58    var scriptLoaded = false;
59    function loadMainDartJs() {
60      if (scriptLoaded) {
61        return;
62      }
63      scriptLoaded = true;
64      var scriptTag = document.createElement('script');
65      scriptTag.src = 'main.dart.js';
66      scriptTag.type = 'application/javascript';
67      document.body.append(scriptTag);
68    }
69
70    if ('serviceWorker' in navigator) {
71      // Service workers are supported. Use them.
72      window.addEventListener('load', function () {
73        // Wait for registration to finish before dropping the &lt;script&gt; tag.
74        // Otherwise, the browser will load the script multiple times,
75        // potentially different versions.
76        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
77        navigator.serviceWorker.register(serviceWorkerUrl)
78          .then((reg) =&gt; {
79            function waitForActivation(serviceWorker) {
80              serviceWorker.addEventListener('statechange', () =&gt; {
81                if (serviceWorker.state == 'activated') {
82                  console.log('Installed new service worker.');
83                  loadMainDartJs();
84                }
85              });
86            }
87            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
88              // No active web worker and we have installed or are installing
89              // one for the first time. Simply wait for it to activate.
90              waitForActivation(reg.installing || reg.waiting);
91            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
92              // When the app updates the serviceWorkerVersion changes, so we
93              // need to ask the service worker to update.
94              console.log('New service worker available.');
95              reg.update();
96              waitForActivation(reg.installing);
97            } else {
98              // Existing service worker is still good.
99              console.log('Loading app from service worker.');
100              loadMainDartJs();
101            }
102          });
103
104        // If service worker doesn't succeed in a reasonable amount of time,
105        // fallback to plaint &lt;script&gt; tag.
106        setTimeout(() =&gt; {
107          if (!scriptLoaded) {
108            console.warn(
109              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
110            );
111            loadMainDartJs();
112          }
113        }, 4000);
114      });
115    } else {
116      // Service workers not supported. Just drop the &lt;script&gt; tag.
117      loadMainDartJs();
118    }
119  &lt;/script&gt;
120  &lt;script type=&quot;module&quot;&gt;
121    // Import the functions you need from the SDKs you need
122    import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js&quot;;
123    import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js&quot;;
124    // TODO: Add SDKs for Firebase products that you want to use
125    // https://firebase.google.com/docs/web/setup#available-libraries
126
127    // Your web app's Firebase configuration
128    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
129    const firebaseConfig = {
130      apiKey: &quot;xxx&quot;,
131      authDomain: &quot;xxx&quot;,
132      projectId: &quot;xx&quot;,
133      storageBucket: &quot;exxx&quot;,
134      messagingSenderId: &quot;xxx&quot;,
135      appId: &quot;xxx&quot;,
136      measurementId: &quot;xxx&quot;
137    };
138
139    // Initialize Firebase
140    const app = initializeApp(firebaseConfig);
141    const analytics = getAnalytics(app);
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145void main() async {
146  WidgetsFlutterBinding.ensureInitialized();
147  await Firebase.initializeApp();
148  runApp(SignUpApp());
149}
150name: signin_example
151description: A new Flutter project.
152
153# The following line prevents the package from being accidentally published to
154# pub.dev using `flutter pub publish`. This is preferred for private packages.
155publish_to: 'none' # Remove this line if you wish to publish to pub.dev
156
157https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
158version: 1.0.0+1
159
160environment:
161  sdk: &quot;&gt;=2.15.0-268.18.beta &lt;3.0.0&quot;
162
163dependencies:
164  flutter:
165    sdk: flutter
166
167
168  # The following adds the Cupertino Icons font to your application.
169  # Use with the CupertinoIcons class for iOS style icons.
170  cupertino_icons: ^1.0.2
171  firebase_auth: ^3.3.0
172  firebase_core: ^1.10.2
173  google_sign_in: ^5.2.1
174  shared_preferences: ^2.0.9
175
176dev_dependencies:
177  flutter_test:
178    sdk: flutter
179
180  flutter_lints: ^1.0.0
181
182# The following section is specific to Flutter.
183flutter:
184
185  assets:
186    - assets/images/
187
188  uses-material-design: true
189

Can anyone help me understand what is the issue here?

ANSWER

Answered 2021-Dec-25 at 09:13

UPDATE:

For your firebase_core version is seems to be sufficient to pass the FirebaseOptions once you initialize firebase in your flutter code (and you don't need any script tags in your index.html):

1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16&lt;!DOCTYPE html&gt;
17&lt;html&gt;
18&lt;head&gt;
19  &lt;!--
20    If you are serving your web app in a path other than the root, change the
21    href value below to reflect the base path you are serving from.
22
23    The path provided below has to start and end with a slash &quot;/&quot; in order for
24    it to work correctly.
25
26    For more details:
27    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
28
29    This is a placeholder for base href that will be replaced by the value of
30    the `--base-href` argument provided to `flutter build`.
31  --&gt;
32  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
33
34  &lt;meta charset=&quot;UTF-8&quot;&gt;
35  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
36  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
37  &lt;meta name=&quot;google-signin-client_id&quot; content=&quot;619218114547-xxxx.apps.googleusercontent.com&quot;&gt;
38  &lt;!-- iOS meta tags &amp; icons --&gt;
39  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
40  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
41  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;signin_example&quot;&gt;
42  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
43  
44  &lt;!-- Favicon --&gt;
45  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
46
47  &lt;title&gt;signin_example&lt;/title&gt;
48  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
49&lt;/head&gt;
50&lt;body&gt;
51  &lt;!-- This script installs service_worker.js to provide PWA functionality to
52       application. For more information, see:
53       https://developers.google.com/web/fundamentals/primers/service-workers --&gt;
54  
55  
56  &lt;script&gt;
57    var serviceWorkerVersion = null;
58    var scriptLoaded = false;
59    function loadMainDartJs() {
60      if (scriptLoaded) {
61        return;
62      }
63      scriptLoaded = true;
64      var scriptTag = document.createElement('script');
65      scriptTag.src = 'main.dart.js';
66      scriptTag.type = 'application/javascript';
67      document.body.append(scriptTag);
68    }
69
70    if ('serviceWorker' in navigator) {
71      // Service workers are supported. Use them.
72      window.addEventListener('load', function () {
73        // Wait for registration to finish before dropping the &lt;script&gt; tag.
74        // Otherwise, the browser will load the script multiple times,
75        // potentially different versions.
76        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
77        navigator.serviceWorker.register(serviceWorkerUrl)
78          .then((reg) =&gt; {
79            function waitForActivation(serviceWorker) {
80              serviceWorker.addEventListener('statechange', () =&gt; {
81                if (serviceWorker.state == 'activated') {
82                  console.log('Installed new service worker.');
83                  loadMainDartJs();
84                }
85              });
86            }
87            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
88              // No active web worker and we have installed or are installing
89              // one for the first time. Simply wait for it to activate.
90              waitForActivation(reg.installing || reg.waiting);
91            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
92              // When the app updates the serviceWorkerVersion changes, so we
93              // need to ask the service worker to update.
94              console.log('New service worker available.');
95              reg.update();
96              waitForActivation(reg.installing);
97            } else {
98              // Existing service worker is still good.
99              console.log('Loading app from service worker.');
100              loadMainDartJs();
101            }
102          });
103
104        // If service worker doesn't succeed in a reasonable amount of time,
105        // fallback to plaint &lt;script&gt; tag.
106        setTimeout(() =&gt; {
107          if (!scriptLoaded) {
108            console.warn(
109              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
110            );
111            loadMainDartJs();
112          }
113        }, 4000);
114      });
115    } else {
116      // Service workers not supported. Just drop the &lt;script&gt; tag.
117      loadMainDartJs();
118    }
119  &lt;/script&gt;
120  &lt;script type=&quot;module&quot;&gt;
121    // Import the functions you need from the SDKs you need
122    import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js&quot;;
123    import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js&quot;;
124    // TODO: Add SDKs for Firebase products that you want to use
125    // https://firebase.google.com/docs/web/setup#available-libraries
126
127    // Your web app's Firebase configuration
128    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
129    const firebaseConfig = {
130      apiKey: &quot;xxx&quot;,
131      authDomain: &quot;xxx&quot;,
132      projectId: &quot;xx&quot;,
133      storageBucket: &quot;exxx&quot;,
134      messagingSenderId: &quot;xxx&quot;,
135      appId: &quot;xxx&quot;,
136      measurementId: &quot;xxx&quot;
137    };
138
139    // Initialize Firebase
140    const app = initializeApp(firebaseConfig);
141    const analytics = getAnalytics(app);
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145void main() async {
146  WidgetsFlutterBinding.ensureInitialized();
147  await Firebase.initializeApp();
148  runApp(SignUpApp());
149}
150name: signin_example
151description: A new Flutter project.
152
153# The following line prevents the package from being accidentally published to
154# pub.dev using `flutter pub publish`. This is preferred for private packages.
155publish_to: 'none' # Remove this line if you wish to publish to pub.dev
156
157https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
158version: 1.0.0+1
159
160environment:
161  sdk: &quot;&gt;=2.15.0-268.18.beta &lt;3.0.0&quot;
162
163dependencies:
164  flutter:
165    sdk: flutter
166
167
168  # The following adds the Cupertino Icons font to your application.
169  # Use with the CupertinoIcons class for iOS style icons.
170  cupertino_icons: ^1.0.2
171  firebase_auth: ^3.3.0
172  firebase_core: ^1.10.2
173  google_sign_in: ^5.2.1
174  shared_preferences: ^2.0.9
175
176dev_dependencies:
177  flutter_test:
178    sdk: flutter
179
180  flutter_lints: ^1.0.0
181
182# The following section is specific to Flutter.
183flutter:
184
185  assets:
186    - assets/images/
187
188  uses-material-design: true
189void main() async {
190  WidgetsFlutterBinding.ensureInitialized();
191  await Firebase.initializeApp(
192    // Replace with actual values
193    options: FirebaseOptions(
194      apiKey: &quot;XXX&quot;,
195      appId: &quot;XXX&quot;,
196      messagingSenderId: &quot;XXX&quot;,
197      projectId: &quot;XXX&quot;,
198    ),
199  );
200  runApp(MyApp());
201}
202

Alternatively, one can also follow the updated official documentation and use the Firebase CLI to automatically create a firebase_options.dart file in your lib folder that will define the correct FirebaseOptions for you. The steps are:

  1. Install Flutterfire CLI:
1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16&lt;!DOCTYPE html&gt;
17&lt;html&gt;
18&lt;head&gt;
19  &lt;!--
20    If you are serving your web app in a path other than the root, change the
21    href value below to reflect the base path you are serving from.
22
23    The path provided below has to start and end with a slash &quot;/&quot; in order for
24    it to work correctly.
25
26    For more details:
27    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
28
29    This is a placeholder for base href that will be replaced by the value of
30    the `--base-href` argument provided to `flutter build`.
31  --&gt;
32  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
33
34  &lt;meta charset=&quot;UTF-8&quot;&gt;
35  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
36  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
37  &lt;meta name=&quot;google-signin-client_id&quot; content=&quot;619218114547-xxxx.apps.googleusercontent.com&quot;&gt;
38  &lt;!-- iOS meta tags &amp; icons --&gt;
39  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
40  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
41  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;signin_example&quot;&gt;
42  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
43  
44  &lt;!-- Favicon --&gt;
45  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
46
47  &lt;title&gt;signin_example&lt;/title&gt;
48  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
49&lt;/head&gt;
50&lt;body&gt;
51  &lt;!-- This script installs service_worker.js to provide PWA functionality to
52       application. For more information, see:
53       https://developers.google.com/web/fundamentals/primers/service-workers --&gt;
54  
55  
56  &lt;script&gt;
57    var serviceWorkerVersion = null;
58    var scriptLoaded = false;
59    function loadMainDartJs() {
60      if (scriptLoaded) {
61        return;
62      }
63      scriptLoaded = true;
64      var scriptTag = document.createElement('script');
65      scriptTag.src = 'main.dart.js';
66      scriptTag.type = 'application/javascript';
67      document.body.append(scriptTag);
68    }
69
70    if ('serviceWorker' in navigator) {
71      // Service workers are supported. Use them.
72      window.addEventListener('load', function () {
73        // Wait for registration to finish before dropping the &lt;script&gt; tag.
74        // Otherwise, the browser will load the script multiple times,
75        // potentially different versions.
76        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
77        navigator.serviceWorker.register(serviceWorkerUrl)
78          .then((reg) =&gt; {
79            function waitForActivation(serviceWorker) {
80              serviceWorker.addEventListener('statechange', () =&gt; {
81                if (serviceWorker.state == 'activated') {
82                  console.log('Installed new service worker.');
83                  loadMainDartJs();
84                }
85              });
86            }
87            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
88              // No active web worker and we have installed or are installing
89              // one for the first time. Simply wait for it to activate.
90              waitForActivation(reg.installing || reg.waiting);
91            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
92              // When the app updates the serviceWorkerVersion changes, so we
93              // need to ask the service worker to update.
94              console.log('New service worker available.');
95              reg.update();
96              waitForActivation(reg.installing);
97            } else {
98              // Existing service worker is still good.
99              console.log('Loading app from service worker.');
100              loadMainDartJs();
101            }
102          });
103
104        // If service worker doesn't succeed in a reasonable amount of time,
105        // fallback to plaint &lt;script&gt; tag.
106        setTimeout(() =&gt; {
107          if (!scriptLoaded) {
108            console.warn(
109              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
110            );
111            loadMainDartJs();
112          }
113        }, 4000);
114      });
115    } else {
116      // Service workers not supported. Just drop the &lt;script&gt; tag.
117      loadMainDartJs();
118    }
119  &lt;/script&gt;
120  &lt;script type=&quot;module&quot;&gt;
121    // Import the functions you need from the SDKs you need
122    import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js&quot;;
123    import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js&quot;;
124    // TODO: Add SDKs for Firebase products that you want to use
125    // https://firebase.google.com/docs/web/setup#available-libraries
126
127    // Your web app's Firebase configuration
128    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
129    const firebaseConfig = {
130      apiKey: &quot;xxx&quot;,
131      authDomain: &quot;xxx&quot;,
132      projectId: &quot;xx&quot;,
133      storageBucket: &quot;exxx&quot;,
134      messagingSenderId: &quot;xxx&quot;,
135      appId: &quot;xxx&quot;,
136      measurementId: &quot;xxx&quot;
137    };
138
139    // Initialize Firebase
140    const app = initializeApp(firebaseConfig);
141    const analytics = getAnalytics(app);
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145void main() async {
146  WidgetsFlutterBinding.ensureInitialized();
147  await Firebase.initializeApp();
148  runApp(SignUpApp());
149}
150name: signin_example
151description: A new Flutter project.
152
153# The following line prevents the package from being accidentally published to
154# pub.dev using `flutter pub publish`. This is preferred for private packages.
155publish_to: 'none' # Remove this line if you wish to publish to pub.dev
156
157https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
158version: 1.0.0+1
159
160environment:
161  sdk: &quot;&gt;=2.15.0-268.18.beta &lt;3.0.0&quot;
162
163dependencies:
164  flutter:
165    sdk: flutter
166
167
168  # The following adds the Cupertino Icons font to your application.
169  # Use with the CupertinoIcons class for iOS style icons.
170  cupertino_icons: ^1.0.2
171  firebase_auth: ^3.3.0
172  firebase_core: ^1.10.2
173  google_sign_in: ^5.2.1
174  shared_preferences: ^2.0.9
175
176dev_dependencies:
177  flutter_test:
178    sdk: flutter
179
180  flutter_lints: ^1.0.0
181
182# The following section is specific to Flutter.
183flutter:
184
185  assets:
186    - assets/images/
187
188  uses-material-design: true
189void main() async {
190  WidgetsFlutterBinding.ensureInitialized();
191  await Firebase.initializeApp(
192    // Replace with actual values
193    options: FirebaseOptions(
194      apiKey: &quot;XXX&quot;,
195      appId: &quot;XXX&quot;,
196      messagingSenderId: &quot;XXX&quot;,
197      projectId: &quot;XXX&quot;,
198    ),
199  );
200  runApp(MyApp());
201}
202dart pub global activate flutterfire_cli
203
  1. Configure Flutterfire (run in your project's root and go through the wizard selecting the correct Firebase project and target platforms):
1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16&lt;!DOCTYPE html&gt;
17&lt;html&gt;
18&lt;head&gt;
19  &lt;!--
20    If you are serving your web app in a path other than the root, change the
21    href value below to reflect the base path you are serving from.
22
23    The path provided below has to start and end with a slash &quot;/&quot; in order for
24    it to work correctly.
25
26    For more details:
27    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
28
29    This is a placeholder for base href that will be replaced by the value of
30    the `--base-href` argument provided to `flutter build`.
31  --&gt;
32  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
33
34  &lt;meta charset=&quot;UTF-8&quot;&gt;
35  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
36  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
37  &lt;meta name=&quot;google-signin-client_id&quot; content=&quot;619218114547-xxxx.apps.googleusercontent.com&quot;&gt;
38  &lt;!-- iOS meta tags &amp; icons --&gt;
39  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
40  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
41  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;signin_example&quot;&gt;
42  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
43  
44  &lt;!-- Favicon --&gt;
45  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
46
47  &lt;title&gt;signin_example&lt;/title&gt;
48  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
49&lt;/head&gt;
50&lt;body&gt;
51  &lt;!-- This script installs service_worker.js to provide PWA functionality to
52       application. For more information, see:
53       https://developers.google.com/web/fundamentals/primers/service-workers --&gt;
54  
55  
56  &lt;script&gt;
57    var serviceWorkerVersion = null;
58    var scriptLoaded = false;
59    function loadMainDartJs() {
60      if (scriptLoaded) {
61        return;
62      }
63      scriptLoaded = true;
64      var scriptTag = document.createElement('script');
65      scriptTag.src = 'main.dart.js';
66      scriptTag.type = 'application/javascript';
67      document.body.append(scriptTag);
68    }
69
70    if ('serviceWorker' in navigator) {
71      // Service workers are supported. Use them.
72      window.addEventListener('load', function () {
73        // Wait for registration to finish before dropping the &lt;script&gt; tag.
74        // Otherwise, the browser will load the script multiple times,
75        // potentially different versions.
76        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
77        navigator.serviceWorker.register(serviceWorkerUrl)
78          .then((reg) =&gt; {
79            function waitForActivation(serviceWorker) {
80              serviceWorker.addEventListener('statechange', () =&gt; {
81                if (serviceWorker.state == 'activated') {
82                  console.log('Installed new service worker.');
83                  loadMainDartJs();
84                }
85              });
86            }
87            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
88              // No active web worker and we have installed or are installing
89              // one for the first time. Simply wait for it to activate.
90              waitForActivation(reg.installing || reg.waiting);
91            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
92              // When the app updates the serviceWorkerVersion changes, so we
93              // need to ask the service worker to update.
94              console.log('New service worker available.');
95              reg.update();
96              waitForActivation(reg.installing);
97            } else {
98              // Existing service worker is still good.
99              console.log('Loading app from service worker.');
100              loadMainDartJs();
101            }
102          });
103
104        // If service worker doesn't succeed in a reasonable amount of time,
105        // fallback to plaint &lt;script&gt; tag.
106        setTimeout(() =&gt; {
107          if (!scriptLoaded) {
108            console.warn(
109              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
110            );
111            loadMainDartJs();
112          }
113        }, 4000);
114      });
115    } else {
116      // Service workers not supported. Just drop the &lt;script&gt; tag.
117      loadMainDartJs();
118    }
119  &lt;/script&gt;
120  &lt;script type=&quot;module&quot;&gt;
121    // Import the functions you need from the SDKs you need
122    import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js&quot;;
123    import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js&quot;;
124    // TODO: Add SDKs for Firebase products that you want to use
125    // https://firebase.google.com/docs/web/setup#available-libraries
126
127    // Your web app's Firebase configuration
128    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
129    const firebaseConfig = {
130      apiKey: &quot;xxx&quot;,
131      authDomain: &quot;xxx&quot;,
132      projectId: &quot;xx&quot;,
133      storageBucket: &quot;exxx&quot;,
134      messagingSenderId: &quot;xxx&quot;,
135      appId: &quot;xxx&quot;,
136      measurementId: &quot;xxx&quot;
137    };
138
139    // Initialize Firebase
140    const app = initializeApp(firebaseConfig);
141    const analytics = getAnalytics(app);
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145void main() async {
146  WidgetsFlutterBinding.ensureInitialized();
147  await Firebase.initializeApp();
148  runApp(SignUpApp());
149}
150name: signin_example
151description: A new Flutter project.
152
153# The following line prevents the package from being accidentally published to
154# pub.dev using `flutter pub publish`. This is preferred for private packages.
155publish_to: 'none' # Remove this line if you wish to publish to pub.dev
156
157https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
158version: 1.0.0+1
159
160environment:
161  sdk: &quot;&gt;=2.15.0-268.18.beta &lt;3.0.0&quot;
162
163dependencies:
164  flutter:
165    sdk: flutter
166
167
168  # The following adds the Cupertino Icons font to your application.
169  # Use with the CupertinoIcons class for iOS style icons.
170  cupertino_icons: ^1.0.2
171  firebase_auth: ^3.3.0
172  firebase_core: ^1.10.2
173  google_sign_in: ^5.2.1
174  shared_preferences: ^2.0.9
175
176dev_dependencies:
177  flutter_test:
178    sdk: flutter
179
180  flutter_lints: ^1.0.0
181
182# The following section is specific to Flutter.
183flutter:
184
185  assets:
186    - assets/images/
187
188  uses-material-design: true
189void main() async {
190  WidgetsFlutterBinding.ensureInitialized();
191  await Firebase.initializeApp(
192    // Replace with actual values
193    options: FirebaseOptions(
194      apiKey: &quot;XXX&quot;,
195      appId: &quot;XXX&quot;,
196      messagingSenderId: &quot;XXX&quot;,
197      projectId: &quot;XXX&quot;,
198    ),
199  );
200  runApp(MyApp());
201}
202dart pub global activate flutterfire_cli
203flutterfire configure
204
  1. Import the automatically generated firebase_options.dart file in your main.dart file and initialize Firebase as follows:
1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16&lt;!DOCTYPE html&gt;
17&lt;html&gt;
18&lt;head&gt;
19  &lt;!--
20    If you are serving your web app in a path other than the root, change the
21    href value below to reflect the base path you are serving from.
22
23    The path provided below has to start and end with a slash &quot;/&quot; in order for
24    it to work correctly.
25
26    For more details:
27    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
28
29    This is a placeholder for base href that will be replaced by the value of
30    the `--base-href` argument provided to `flutter build`.
31  --&gt;
32  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
33
34  &lt;meta charset=&quot;UTF-8&quot;&gt;
35  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
36  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
37  &lt;meta name=&quot;google-signin-client_id&quot; content=&quot;619218114547-xxxx.apps.googleusercontent.com&quot;&gt;
38  &lt;!-- iOS meta tags &amp; icons --&gt;
39  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
40  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
41  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;signin_example&quot;&gt;
42  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
43  
44  &lt;!-- Favicon --&gt;
45  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
46
47  &lt;title&gt;signin_example&lt;/title&gt;
48  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
49&lt;/head&gt;
50&lt;body&gt;
51  &lt;!-- This script installs service_worker.js to provide PWA functionality to
52       application. For more information, see:
53       https://developers.google.com/web/fundamentals/primers/service-workers --&gt;
54  
55  
56  &lt;script&gt;
57    var serviceWorkerVersion = null;
58    var scriptLoaded = false;
59    function loadMainDartJs() {
60      if (scriptLoaded) {
61        return;
62      }
63      scriptLoaded = true;
64      var scriptTag = document.createElement('script');
65      scriptTag.src = 'main.dart.js';
66      scriptTag.type = 'application/javascript';
67      document.body.append(scriptTag);
68    }
69
70    if ('serviceWorker' in navigator) {
71      // Service workers are supported. Use them.
72      window.addEventListener('load', function () {
73        // Wait for registration to finish before dropping the &lt;script&gt; tag.
74        // Otherwise, the browser will load the script multiple times,
75        // potentially different versions.
76        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
77        navigator.serviceWorker.register(serviceWorkerUrl)
78          .then((reg) =&gt; {
79            function waitForActivation(serviceWorker) {
80              serviceWorker.addEventListener('statechange', () =&gt; {
81                if (serviceWorker.state == 'activated') {
82                  console.log('Installed new service worker.');
83                  loadMainDartJs();
84                }
85              });
86            }
87            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
88              // No active web worker and we have installed or are installing
89              // one for the first time. Simply wait for it to activate.
90              waitForActivation(reg.installing || reg.waiting);
91            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
92              // When the app updates the serviceWorkerVersion changes, so we
93              // need to ask the service worker to update.
94              console.log('New service worker available.');
95              reg.update();
96              waitForActivation(reg.installing);
97            } else {
98              // Existing service worker is still good.
99              console.log('Loading app from service worker.');
100              loadMainDartJs();
101            }
102          });
103
104        // If service worker doesn't succeed in a reasonable amount of time,
105        // fallback to plaint &lt;script&gt; tag.
106        setTimeout(() =&gt; {
107          if (!scriptLoaded) {
108            console.warn(
109              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
110            );
111            loadMainDartJs();
112          }
113        }, 4000);
114      });
115    } else {
116      // Service workers not supported. Just drop the &lt;script&gt; tag.
117      loadMainDartJs();
118    }
119  &lt;/script&gt;
120  &lt;script type=&quot;module&quot;&gt;
121    // Import the functions you need from the SDKs you need
122    import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js&quot;;
123    import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js&quot;;
124    // TODO: Add SDKs for Firebase products that you want to use
125    // https://firebase.google.com/docs/web/setup#available-libraries
126
127    // Your web app's Firebase configuration
128    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
129    const firebaseConfig = {
130      apiKey: &quot;xxx&quot;,
131      authDomain: &quot;xxx&quot;,
132      projectId: &quot;xx&quot;,
133      storageBucket: &quot;exxx&quot;,
134      messagingSenderId: &quot;xxx&quot;,
135      appId: &quot;xxx&quot;,
136      measurementId: &quot;xxx&quot;
137    };
138
139    // Initialize Firebase
140    const app = initializeApp(firebaseConfig);
141    const analytics = getAnalytics(app);
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145void main() async {
146  WidgetsFlutterBinding.ensureInitialized();
147  await Firebase.initializeApp();
148  runApp(SignUpApp());
149}
150name: signin_example
151description: A new Flutter project.
152
153# The following line prevents the package from being accidentally published to
154# pub.dev using `flutter pub publish`. This is preferred for private packages.
155publish_to: 'none' # Remove this line if you wish to publish to pub.dev
156
157https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
158version: 1.0.0+1
159
160environment:
161  sdk: &quot;&gt;=2.15.0-268.18.beta &lt;3.0.0&quot;
162
163dependencies:
164  flutter:
165    sdk: flutter
166
167
168  # The following adds the Cupertino Icons font to your application.
169  # Use with the CupertinoIcons class for iOS style icons.
170  cupertino_icons: ^1.0.2
171  firebase_auth: ^3.3.0
172  firebase_core: ^1.10.2
173  google_sign_in: ^5.2.1
174  shared_preferences: ^2.0.9
175
176dev_dependencies:
177  flutter_test:
178    sdk: flutter
179
180  flutter_lints: ^1.0.0
181
182# The following section is specific to Flutter.
183flutter:
184
185  assets:
186    - assets/images/
187
188  uses-material-design: true
189void main() async {
190  WidgetsFlutterBinding.ensureInitialized();
191  await Firebase.initializeApp(
192    // Replace with actual values
193    options: FirebaseOptions(
194      apiKey: &quot;XXX&quot;,
195      appId: &quot;XXX&quot;,
196      messagingSenderId: &quot;XXX&quot;,
197      projectId: &quot;XXX&quot;,
198    ),
199  );
200  runApp(MyApp());
201}
202dart pub global activate flutterfire_cli
203flutterfire configure
204void main() async {
205  WidgetsFlutterBinding.ensureInitialized();
206  await Firebase.initializeApp(
207    options: DefaultFirebaseOptions.currentPlatform,
208  );
209  runApp(MyApp());
210}
211

PREVIOUS ANSWER:

From the docs:

The only way to currently add the Firebase SDKs to your Flutter web project is by importing the scripts from the Firebase content delivery network (CDN).

Therefore, please try to use script tags to import the relevant firebase components with version 8.6.1 as shown below (more info here):

1&quot;FirebaseOptions cannot be null when creating the default app.&quot;
2    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
3    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
4at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
5    at initializeApp.next (&lt;anonymous&gt;)
6    at http://localhost:7357/dart_sdk.js:40192:33
7    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
8    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
9    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
10    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
11    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
12    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
13    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
14    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
15    at http://localhost:7357/dart_sdk.js:35811:9
16&lt;!DOCTYPE html&gt;
17&lt;html&gt;
18&lt;head&gt;
19  &lt;!--
20    If you are serving your web app in a path other than the root, change the
21    href value below to reflect the base path you are serving from.
22
23    The path provided below has to start and end with a slash &quot;/&quot; in order for
24    it to work correctly.
25
26    For more details:
27    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
28
29    This is a placeholder for base href that will be replaced by the value of
30    the `--base-href` argument provided to `flutter build`.
31  --&gt;
32  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
33
34  &lt;meta charset=&quot;UTF-8&quot;&gt;
35  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
36  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
37  &lt;meta name=&quot;google-signin-client_id&quot; content=&quot;619218114547-xxxx.apps.googleusercontent.com&quot;&gt;
38  &lt;!-- iOS meta tags &amp; icons --&gt;
39  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
40  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
41  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;signin_example&quot;&gt;
42  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
43  
44  &lt;!-- Favicon --&gt;
45  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; href=&quot;favicon.png&quot;/&gt;
46
47  &lt;title&gt;signin_example&lt;/title&gt;
48  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
49&lt;/head&gt;
50&lt;body&gt;
51  &lt;!-- This script installs service_worker.js to provide PWA functionality to
52       application. For more information, see:
53       https://developers.google.com/web/fundamentals/primers/service-workers --&gt;
54  
55  
56  &lt;script&gt;
57    var serviceWorkerVersion = null;
58    var scriptLoaded = false;
59    function loadMainDartJs() {
60      if (scriptLoaded) {
61        return;
62      }
63      scriptLoaded = true;
64      var scriptTag = document.createElement('script');
65      scriptTag.src = 'main.dart.js';
66      scriptTag.type = 'application/javascript';
67      document.body.append(scriptTag);
68    }
69
70    if ('serviceWorker' in navigator) {
71      // Service workers are supported. Use them.
72      window.addEventListener('load', function () {
73        // Wait for registration to finish before dropping the &lt;script&gt; tag.
74        // Otherwise, the browser will load the script multiple times,
75        // potentially different versions.
76        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
77        navigator.serviceWorker.register(serviceWorkerUrl)
78          .then((reg) =&gt; {
79            function waitForActivation(serviceWorker) {
80              serviceWorker.addEventListener('statechange', () =&gt; {
81                if (serviceWorker.state == 'activated') {
82                  console.log('Installed new service worker.');
83                  loadMainDartJs();
84                }
85              });
86            }
87            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
88              // No active web worker and we have installed or are installing
89              // one for the first time. Simply wait for it to activate.
90              waitForActivation(reg.installing || reg.waiting);
91            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
92              // When the app updates the serviceWorkerVersion changes, so we
93              // need to ask the service worker to update.
94              console.log('New service worker available.');
95              reg.update();
96              waitForActivation(reg.installing);
97            } else {
98              // Existing service worker is still good.
99              console.log('Loading app from service worker.');
100              loadMainDartJs();
101            }
102          });
103
104        // If service worker doesn't succeed in a reasonable amount of time,
105        // fallback to plaint &lt;script&gt; tag.
106        setTimeout(() =&gt; {
107          if (!scriptLoaded) {
108            console.warn(
109              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
110            );
111            loadMainDartJs();
112          }
113        }, 4000);
114      });
115    } else {
116      // Service workers not supported. Just drop the &lt;script&gt; tag.
117      loadMainDartJs();
118    }
119  &lt;/script&gt;
120  &lt;script type=&quot;module&quot;&gt;
121    // Import the functions you need from the SDKs you need
122    import { initializeApp } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js&quot;;
123    import { getAnalytics } from &quot;https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js&quot;;
124    // TODO: Add SDKs for Firebase products that you want to use
125    // https://firebase.google.com/docs/web/setup#available-libraries
126
127    // Your web app's Firebase configuration
128    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
129    const firebaseConfig = {
130      apiKey: &quot;xxx&quot;,
131      authDomain: &quot;xxx&quot;,
132      projectId: &quot;xx&quot;,
133      storageBucket: &quot;exxx&quot;,
134      messagingSenderId: &quot;xxx&quot;,
135      appId: &quot;xxx&quot;,
136      measurementId: &quot;xxx&quot;
137    };
138
139    // Initialize Firebase
140    const app = initializeApp(firebaseConfig);
141    const analytics = getAnalytics(app);
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145void main() async {
146  WidgetsFlutterBinding.ensureInitialized();
147  await Firebase.initializeApp();
148  runApp(SignUpApp());
149}
150name: signin_example
151description: A new Flutter project.
152
153# The following line prevents the package from being accidentally published to
154# pub.dev using `flutter pub publish`. This is preferred for private packages.
155publish_to: 'none' # Remove this line if you wish to publish to pub.dev
156
157https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
158version: 1.0.0+1
159
160environment:
161  sdk: &quot;&gt;=2.15.0-268.18.beta &lt;3.0.0&quot;
162
163dependencies:
164  flutter:
165    sdk: flutter
166
167
168  # The following adds the Cupertino Icons font to your application.
169  # Use with the CupertinoIcons class for iOS style icons.
170  cupertino_icons: ^1.0.2
171  firebase_auth: ^3.3.0
172  firebase_core: ^1.10.2
173  google_sign_in: ^5.2.1
174  shared_preferences: ^2.0.9
175
176dev_dependencies:
177  flutter_test:
178    sdk: flutter
179
180  flutter_lints: ^1.0.0
181
182# The following section is specific to Flutter.
183flutter:
184
185  assets:
186    - assets/images/
187
188  uses-material-design: true
189void main() async {
190  WidgetsFlutterBinding.ensureInitialized();
191  await Firebase.initializeApp(
192    // Replace with actual values
193    options: FirebaseOptions(
194      apiKey: &quot;XXX&quot;,
195      appId: &quot;XXX&quot;,
196      messagingSenderId: &quot;XXX&quot;,
197      projectId: &quot;XXX&quot;,
198    ),
199  );
200  runApp(MyApp());
201}
202dart pub global activate flutterfire_cli
203flutterfire configure
204void main() async {
205  WidgetsFlutterBinding.ensureInitialized();
206  await Firebase.initializeApp(
207    options: DefaultFirebaseOptions.currentPlatform,
208  );
209  runApp(MyApp());
210}
211  &lt;script src=&quot;https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js&quot;&gt;&lt;/script&gt;
212  &lt;script src=&quot;https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js&quot;&gt;&lt;/script&gt;
213  &lt;script&gt;
214    var firebaseConfig = {
215      apiKey: &quot;xxx&quot;,
216      authDomain: &quot;xxx&quot;,
217      projectId: &quot;xx&quot;,
218      storageBucket: &quot;exxx&quot;,
219      messagingSenderId: &quot;xxx&quot;,
220      appId: &quot;xxx&quot;,
221      measurementId: &quot;xxx&quot;
222    };
223
224    firebase.initializeApp(firebaseConfig);
225    firebase.analytics();
226  &lt;/script&gt;
227

Source https://stackoverflow.com/questions/70232931

QUESTION

Wrong og:image is appearing on page metadata

Asked 2021-Dec-22 at 02:16

In my [id].tsx page I have the following meta tag structure

1&lt;Head&gt;
2  &lt;meta property=&quot;og:title&quot; content={'품고 - ' + archive.title} key=&quot;title&quot; /&gt;
3  &lt;meta property=&quot;og:type&quot; content=&quot;article&quot; key=&quot;type&quot; /&gt;
4  {imageUrl &amp;&amp; &lt;meta property=&quot;og:image&quot; content={imageUrl} key=&quot;image&quot; /&gt;}
5&lt;/Head&gt;
6

However in my production server, when I scrape an article using the Facebook debugger I get the following error

enter image description here

But when I check for an article in my development server, the proper image shows even though the code is the same as production

enter image description here

I also do have the following line in my _app.tsx file that I think may be causing the error but am not sure

1&lt;Head&gt;
2  &lt;meta property=&quot;og:title&quot; content={'품고 - ' + archive.title} key=&quot;title&quot; /&gt;
3  &lt;meta property=&quot;og:type&quot; content=&quot;article&quot; key=&quot;type&quot; /&gt;
4  {imageUrl &amp;&amp; &lt;meta property=&quot;og:image&quot; content={imageUrl} key=&quot;image&quot; /&gt;}
5&lt;/Head&gt;
6&lt;link rel=&quot;canonical&quot; href=&quot;https://poomgo.com/&quot; /&gt;
7

And the truly strange thing is that if I share my production article links on kakao, the thumbnail image shows up fine, but on Facebook and LinkedIn, the thumbnail image does not show up properly.

Does anyone know why my meta tags are scraped differently on my production and development servers when the code applied is exactly the same?


How my imageUrl is generated

I get archive data from a third party API (strapi) using useSWR

1&lt;Head&gt;
2  &lt;meta property=&quot;og:title&quot; content={'품고 - ' + archive.title} key=&quot;title&quot; /&gt;
3  &lt;meta property=&quot;og:type&quot; content=&quot;article&quot; key=&quot;type&quot; /&gt;
4  {imageUrl &amp;&amp; &lt;meta property=&quot;og:image&quot; content={imageUrl} key=&quot;image&quot; /&gt;}
5&lt;/Head&gt;
6&lt;link rel=&quot;canonical&quot; href=&quot;https://poomgo.com/&quot; /&gt;
7const { data: archive, error } = useSWR('/archives/' + router.query.id, (url) =&gt; {
8    return axios.get(url).then(res =&gt; res.data)
9  }, {
10    initialData: props.data
11  })
12

I then get my images from the archives and if images exist, I get my imageUrl

1&lt;Head&gt;
2  &lt;meta property=&quot;og:title&quot; content={'품고 - ' + archive.title} key=&quot;title&quot; /&gt;
3  &lt;meta property=&quot;og:type&quot; content=&quot;article&quot; key=&quot;type&quot; /&gt;
4  {imageUrl &amp;&amp; &lt;meta property=&quot;og:image&quot; content={imageUrl} key=&quot;image&quot; /&gt;}
5&lt;/Head&gt;
6&lt;link rel=&quot;canonical&quot; href=&quot;https://poomgo.com/&quot; /&gt;
7const { data: archive, error } = useSWR('/archives/' + router.query.id, (url) =&gt; {
8    return axios.get(url).then(res =&gt; res.data)
9  }, {
10    initialData: props.data
11  })
12const images = archive.images
13  let imageUrl = ''
14
15  if (images &amp;&amp; images.length &gt; 0) {
16    imageUrl = getCloundFrontUrl(images[0].url)
17  }
18

I then use the getCloundFrontUrl function to replace the url with my cdn

1&lt;Head&gt;
2  &lt;meta property=&quot;og:title&quot; content={'품고 - ' + archive.title} key=&quot;title&quot; /&gt;
3  &lt;meta property=&quot;og:type&quot; content=&quot;article&quot; key=&quot;type&quot; /&gt;
4  {imageUrl &amp;&amp; &lt;meta property=&quot;og:image&quot; content={imageUrl} key=&quot;image&quot; /&gt;}
5&lt;/Head&gt;
6&lt;link rel=&quot;canonical&quot; href=&quot;https://poomgo.com/&quot; /&gt;
7const { data: archive, error } = useSWR('/archives/' + router.query.id, (url) =&gt; {
8    return axios.get(url).then(res =&gt; res.data)
9  }, {
10    initialData: props.data
11  })
12const images = archive.images
13  let imageUrl = ''
14
15  if (images &amp;&amp; images.length &gt; 0) {
16    imageUrl = getCloundFrontUrl(images[0].url)
17  }
18export const getCloundFrontUrl = (url) =&gt; {
19  return url ? url.replace('poomgo-homepage.s3.ap-northeast-2.amazonaws.com', 'cdn-hp.poomgo.com') : ''
20}
21

Below is the shape of my data

enter image description here

ANSWER

Answered 2021-Dec-22 at 02:16

I removed the

1&lt;Head&gt;
2  &lt;meta property=&quot;og:title&quot; content={'품고 - ' + archive.title} key=&quot;title&quot; /&gt;
3  &lt;meta property=&quot;og:type&quot; content=&quot;article&quot; key=&quot;type&quot; /&gt;
4  {imageUrl &amp;&amp; &lt;meta property=&quot;og:image&quot; content={imageUrl} key=&quot;image&quot; /&gt;}
5&lt;/Head&gt;
6&lt;link rel=&quot;canonical&quot; href=&quot;https://poomgo.com/&quot; /&gt;
7const { data: archive, error } = useSWR('/archives/' + router.query.id, (url) =&gt; {
8    return axios.get(url).then(res =&gt; res.data)
9  }, {
10    initialData: props.data
11  })
12const images = archive.images
13  let imageUrl = ''
14
15  if (images &amp;&amp; images.length &gt; 0) {
16    imageUrl = getCloundFrontUrl(images[0].url)
17  }
18export const getCloundFrontUrl = (url) =&gt; {
19  return url ? url.replace('poomgo-homepage.s3.ap-northeast-2.amazonaws.com', 'cdn-hp.poomgo.com') : ''
20}
21&lt;link rel=&quot;canonical&quot; href=&quot;https://poomgo.com/&quot; /&gt;
22

from my _app.tsx and the issue was resolved. Pretty sure that the code above signalled redirects to my home page from every page on production which caused the wrong og:image

Source https://stackoverflow.com/questions/70432631

QUESTION

React js change meta tags dynamically

Asked 2021-Dec-20 at 07:50

I have two flow of my application one is user side the other is admin side. My user side is responsive so i want meta tag to say <meta name="viewport" content="width=device-width, initial-scale=1" /> and my admin side is not responsive so i want to enforce browser to open in desktop mode which requires this meta tag to be like this <meta name="viewport" content="width=1024" />

I am using react-document-meta with the following objects

1const metaUser = {
2  title: &quot;User meta tags&quot;,
3  description: &quot;Basically make the application responsive when on user side&quot;,
4  meta: {
5    name: { keywords: &quot;viewport&quot; },
6    content: &quot;width=device-width, initial-scale=1&quot;,
7  },
8};
9const metaAdmin = {
10  title: &quot;Admin meta tags&quot;,
11  description: &quot;Make the application default in desktop mode&quot;,
12  meta: {
13    name: { keywords: &quot;viewport&quot; },
14    content: &quot;width=1024&quot;,
15  },
16};
17

but it creates new meta on the head tag and those tags doesn't work

enter image description here

ANSWER

Answered 2021-Dec-20 at 07:50

I suggest using react-helmet.

You can install it using the npm command: npm i react-helmet

And then import in in your component/page:

1const metaUser = {
2  title: &quot;User meta tags&quot;,
3  description: &quot;Basically make the application responsive when on user side&quot;,
4  meta: {
5    name: { keywords: &quot;viewport&quot; },
6    content: &quot;width=device-width, initial-scale=1&quot;,
7  },
8};
9const metaAdmin = {
10  title: &quot;Admin meta tags&quot;,
11  description: &quot;Make the application default in desktop mode&quot;,
12  meta: {
13    name: { keywords: &quot;viewport&quot; },
14    content: &quot;width=1024&quot;,
15  },
16};
17import {Helmet} from &quot;react-helmet&quot;;
18

And use all your tags inside the Helmet component, which you would put inside the regular head tag in html, with the syntax of jsx

1const metaUser = {
2  title: &quot;User meta tags&quot;,
3  description: &quot;Basically make the application responsive when on user side&quot;,
4  meta: {
5    name: { keywords: &quot;viewport&quot; },
6    content: &quot;width=device-width, initial-scale=1&quot;,
7  },
8};
9const metaAdmin = {
10  title: &quot;Admin meta tags&quot;,
11  description: &quot;Make the application default in desktop mode&quot;,
12  meta: {
13    name: { keywords: &quot;viewport&quot; },
14    content: &quot;width=1024&quot;,
15  },
16};
17import {Helmet} from &quot;react-helmet&quot;;
18
19    &lt;Helmet&gt;
20        &lt;title&gt;{`${admin ? &quot;Admin Title&quot; : &quot;Client Title&quot;}`}&lt;/title&gt;
21        &lt;meta name=&quot;description&quot; content={`${admin ? &quot;Admin Content&quot; : &quot;Client Content&quot;}`} /&gt;
22    &lt;/Helmet&gt;
23
24

Source https://stackoverflow.com/questions/70418527

QUESTION

Why is blazor HeadOutlet rendering after the App

Asked 2021-Nov-01 at 19:31

I'm using a HeadOutlet on a server side pre-rendered net6.0 app to set some header tags such as meta description but the server renders the app first and then the headers which makes search engines ignore it.

1@page &quot;/&quot;
2@namespace Example.Pages
3@using Microsoft.AspNetCore.Components.Web
4@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
5
6@{
7    Layout = null;
8}
9
10&lt;!DOCTYPE html&gt;
11&lt;html lang=&quot;en&quot;&gt;
12&lt;head&gt;
13    &lt;component type=&quot;typeof(HeadOutlet)&quot; render-mode=&quot;ServerPrerendered&quot; /&gt;
14    &lt;base href=&quot;~/&quot; /&gt;
15
16    &lt;link href=&quot;css/site.css&quot; rel=&quot;stylesheet&quot; /&gt;
17    &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot;&gt;
18&lt;/head&gt;
19&lt;body&gt;
20    &lt;component type=&quot;typeof(App)&quot; render-mode=&quot;ServerPrerendered&quot; /&gt;
21
22    &lt;div id=&quot;blazor-error-ui&quot;&gt;
23        &lt;environment include=&quot;Staging,Production&quot;&gt;
24            An error has occurred. This application may no longer respond until reloaded.
25        &lt;/environment&gt;
26        &lt;environment include=&quot;Development&quot;&gt;
27            An unhandled exception has occurred. See browser dev tools for details.
28        &lt;/environment&gt;
29        &lt;a href=&quot;/&quot; class=&quot;reload&quot;&gt;Reload&lt;/a&gt;
30        &lt;a href=&quot;#&quot; class=&quot;dismiss&quot;&gt;🗙&lt;/a&gt;
31    &lt;/div&gt;
32
33    &lt;script src=&quot;_framework/blazor.server.js&quot;&gt;&lt;/script&gt;
34    &lt;script src=&quot;~/outsideHandleContainerJsInterop.js&quot;&gt;&lt;/script&gt;
35&lt;/body&gt;
36&lt;/html&gt;
37
1@page &quot;/&quot;
2@namespace Example.Pages
3@using Microsoft.AspNetCore.Components.Web
4@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
5
6@{
7    Layout = null;
8}
9
10&lt;!DOCTYPE html&gt;
11&lt;html lang=&quot;en&quot;&gt;
12&lt;head&gt;
13    &lt;component type=&quot;typeof(HeadOutlet)&quot; render-mode=&quot;ServerPrerendered&quot; /&gt;
14    &lt;base href=&quot;~/&quot; /&gt;
15
16    &lt;link href=&quot;css/site.css&quot; rel=&quot;stylesheet&quot; /&gt;
17    &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot;&gt;
18&lt;/head&gt;
19&lt;body&gt;
20    &lt;component type=&quot;typeof(App)&quot; render-mode=&quot;ServerPrerendered&quot; /&gt;
21
22    &lt;div id=&quot;blazor-error-ui&quot;&gt;
23        &lt;environment include=&quot;Staging,Production&quot;&gt;
24            An error has occurred. This application may no longer respond until reloaded.
25        &lt;/environment&gt;
26        &lt;environment include=&quot;Development&quot;&gt;
27            An unhandled exception has occurred. See browser dev tools for details.
28        &lt;/environment&gt;
29        &lt;a href=&quot;/&quot; class=&quot;reload&quot;&gt;Reload&lt;/a&gt;
30        &lt;a href=&quot;#&quot; class=&quot;dismiss&quot;&gt;🗙&lt;/a&gt;
31    &lt;/div&gt;
32
33    &lt;script src=&quot;_framework/blazor.server.js&quot;&gt;&lt;/script&gt;
34    &lt;script src=&quot;~/outsideHandleContainerJsInterop.js&quot;&gt;&lt;/script&gt;
35&lt;/body&gt;
36&lt;/html&gt;
37@page &quot;/test&quot;
38
39&lt;HeadContent&gt;
40     &lt;meta name=&quot;description&quot; content=&quot;Hello World&quot;&gt;
41&lt;/HeadContent&gt;
42

Viewing the page in a browser will render the meta tags in the head as expected but doing a get request in insomnia/postman returns the initial headers and a blazor pre-render tag comment

1@page &quot;/&quot;
2@namespace Example.Pages
3@using Microsoft.AspNetCore.Components.Web
4@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
5
6@{
7    Layout = null;
8}
9
10&lt;!DOCTYPE html&gt;
11&lt;html lang=&quot;en&quot;&gt;
12&lt;head&gt;
13    &lt;component type=&quot;typeof(HeadOutlet)&quot; render-mode=&quot;ServerPrerendered&quot; /&gt;
14    &lt;base href=&quot;~/&quot; /&gt;
15
16    &lt;link href=&quot;css/site.css&quot; rel=&quot;stylesheet&quot; /&gt;
17    &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot;&gt;
18&lt;/head&gt;
19&lt;body&gt;
20    &lt;component type=&quot;typeof(App)&quot; render-mode=&quot;ServerPrerendered&quot; /&gt;
21
22    &lt;div id=&quot;blazor-error-ui&quot;&gt;
23        &lt;environment include=&quot;Staging,Production&quot;&gt;
24            An error has occurred. This application may no longer respond until reloaded.
25        &lt;/environment&gt;
26        &lt;environment include=&quot;Development&quot;&gt;
27            An unhandled exception has occurred. See browser dev tools for details.
28        &lt;/environment&gt;
29        &lt;a href=&quot;/&quot; class=&quot;reload&quot;&gt;Reload&lt;/a&gt;
30        &lt;a href=&quot;#&quot; class=&quot;dismiss&quot;&gt;🗙&lt;/a&gt;
31    &lt;/div&gt;
32
33    &lt;script src=&quot;_framework/blazor.server.js&quot;&gt;&lt;/script&gt;
34    &lt;script src=&quot;~/outsideHandleContainerJsInterop.js&quot;&gt;&lt;/script&gt;
35&lt;/body&gt;
36&lt;/html&gt;
37@page &quot;/test&quot;
38
39&lt;HeadContent&gt;
40     &lt;meta name=&quot;description&quot; content=&quot;Hello World&quot;&gt;
41&lt;/HeadContent&gt;
42&lt;!--Blazor:{&quot;sequence&quot;:0,&quot;type&quot;:&quot;server&quot;,&quot;prerenderId&quot;:&quot;b0376004567c4aaf9c07defc4341e21e&quot;,&quot;descriptor&quot;:&quot;&lt;long string here&gt;&quot;}--&gt;&lt;!--Blazor:{&quot;prerenderId&quot;:&quot;b0376004567c4aaf9c07defc4341e21e&quot;}--&gt;
43

Is this a bug or am I missing something? I need the head to be rendered before or with the rest of the page so search engines can pick it up.

ANSWER

Answered 2021-Nov-01 at 19:31

This was solved by moving the html/head/body from _Host.cshtml to _Layout.html. More info described in this post: https://github.com/dotnet/aspnetcore/issues/37293

Source https://stackoverflow.com/questions/69696287

QUESTION

Can't link flutter web application to firebase project / infinite loading

Asked 2021-Oct-28 at 10:21

I have a problem when I try to link my Flutter web project to my Firebase. I add the elements, imports and SDK and when I touch the main.dart to initialize the firebase functions, even if the code doesn't show any error, when I launch the application from my IDE with google, I'm facing an infinite loading screen. And sometimes there is not even the blue loading bar. All the SDK, my IDE and my frameworks are up to date in stable version.

I have configured a firebase project with only this application and I Initialized a firestore database like I saw in the CRUD that I followed.

link of the CRUD: https://www.youtube.com/watch?v=Ue_dIKOMcb4&t=1009s

But I don't think it come from the project because I can't even initialize Firebase in the default flutter counter new application.

And in my index.HTML, in the firebase config paragraph, my API key is underlined in RED

Maybe I use the wrong methode to initialize Firebase fuctions in my project, so please can someone show me how to do.

Here's my pubspec.yaml:

1name: flutter_web_diary
2description: A new Flutter project.
3
4version: 1.0.0+1
5
6environment:
7  sdk: &quot;&gt;=2.6.0 &lt;3.0.0&quot;
8
9dependencies:
10  flutter:
11    sdk: flutter
12  provider: ^4.0.4
13  firebase_core: &quot;^1.7.0&quot;
14  cloud_firestore: &quot;^2.5.3&quot;
15
16  cupertino_icons: ^0.1.2
17
18dev_dependencies:
19  flutter_test:
20    sdk: flutter
21
22flutter:
23  uses-material-design: true
24
25

My idex.HTML :

1name: flutter_web_diary
2description: A new Flutter project.
3
4version: 1.0.0+1
5
6environment:
7  sdk: &quot;&gt;=2.6.0 &lt;3.0.0&quot;
8
9dependencies:
10  flutter:
11    sdk: flutter
12  provider: ^4.0.4
13  firebase_core: &quot;^1.7.0&quot;
14  cloud_firestore: &quot;^2.5.3&quot;
15
16  cupertino_icons: ^0.1.2
17
18dev_dependencies:
19  flutter_test:
20    sdk: flutter
21
22flutter:
23  uses-material-design: true
24
25&lt;!DOCTYPE html&gt;
26&lt;html lang=&quot;en&quot;&gt;
27&lt;head&gt;
28  &lt;!--
29    If you are serving your web app in a path other than the root, change the
30    href value below to reflect the base path you are serving from.
31
32    The path provided below has to start and end with a slash &quot;/&quot; in order for
33    it to work correctly.
34
35    For more details:
36    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
37
38    This is a placeholder for base href that will be replaced by the value of
39    the `--base-href` argument provided to `flutter build`.
40  --&gt;
41  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
42
43  &lt;meta charset=&quot;UTF-8&quot;&gt;
44  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
45  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
46
47  &lt;!-- iOS meta tags &amp; icons --&gt;
48  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
49  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
50  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;flutter_application_1&quot;&gt;
51  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
52
53  &lt;title&gt;flutter_application_1&lt;/title&gt;
54  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
55&lt;/head&gt;
56&lt;body&gt;
57  
58  &lt;script&gt;
59    import { initializeApp } from &quot;firebase/app&quot;;
60    import { } from &quot;https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js&quot;
61    import { } from &quot;https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js&quot;
62// TODO: Add SDKs for Firebase products that you want to use
63// https://firebase.google.com/docs/web/setup#available-libraries
64
65// Your web app's Firebase configuration
66    const firebaseConfig = {
67      apiKey: &quot;...&quot;,
68      authDomain: &quot;...&quot;,
69      databaseURL: &quot;...&quot;,
70      projectId: &quot;...&quot;,
71      storageBucket: &quot;...&quot;,
72      messagingSenderId: &quot;...&quot;,
73      appId: &quot;...&quot;
74    };
75
76// Initialize Firebase
77const app = initializeApp(firebaseConfig);
78  // Initialize Firebase
79  firebase.initializeApp(firebaseConfig);
80    var serviceWorkerVersion = null;
81    var scriptLoaded = false;
82    function loadMainDartJs() {
83      if (scriptLoaded) {
84        return;
85      }
86      scriptLoaded = true;
87      var scriptTag = document.createElement('script');
88      scriptTag.src = 'main.dart.js';
89      scriptTag.type = 'application/javascript';
90      document.body.append(scriptTag);
91    }
92
93    if ('serviceWorker' in navigator) {
94      // Service workers are supported. Use them.
95      window.addEventListener('load', function () {
96        // Wait for registration to finish before dropping the &lt;script&gt; tag.
97        // Otherwise, the browser will load the script multiple times,
98        // potentially different versions.
99        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
100        navigator.serviceWorker.register(serviceWorkerUrl)
101          .then((reg) =&gt; {
102            function waitForActivation(serviceWorker) {
103              serviceWorker.addEventListener('statechange', () =&gt; {
104                if (serviceWorker.state == 'activated') {
105                  console.log('Installed new service worker.');
106                  loadMainDartJs();
107                }
108              });
109            }
110            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
111              // No active web worker and we have installed or are installing
112              // one for the first time. Simply wait for it to activate.
113              waitForActivation(reg.installing || reg.waiting);
114            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
115              // When the app updates the serviceWorkerVersion changes, so we
116              // need to ask the service worker to update.
117              console.log('New service worker available.');
118              reg.update();
119              waitForActivation(reg.installing);
120            } else {
121              // Existing service worker is still good.
122              console.log('Loading app from service worker.');
123              loadMainDartJs();
124            }
125          });
126
127        // If service worker doesn't succeed in a reasonable amount of time,
128        // fallback to plaint &lt;script&gt; tag.
129        setTimeout(() =&gt; {
130          if (!scriptLoaded) {
131            console.warn(
132              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
133            );
134            loadMainDartJs();
135          }
136        }, 4000);
137      });
138    } else {
139      // Service workers not supported. Just drop the &lt;script&gt; tag.
140      loadMainDartJs();
141    }
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145

and my main.dart:

1name: flutter_web_diary
2description: A new Flutter project.
3
4version: 1.0.0+1
5
6environment:
7  sdk: &quot;&gt;=2.6.0 &lt;3.0.0&quot;
8
9dependencies:
10  flutter:
11    sdk: flutter
12  provider: ^4.0.4
13  firebase_core: &quot;^1.7.0&quot;
14  cloud_firestore: &quot;^2.5.3&quot;
15
16  cupertino_icons: ^0.1.2
17
18dev_dependencies:
19  flutter_test:
20    sdk: flutter
21
22flutter:
23  uses-material-design: true
24
25&lt;!DOCTYPE html&gt;
26&lt;html lang=&quot;en&quot;&gt;
27&lt;head&gt;
28  &lt;!--
29    If you are serving your web app in a path other than the root, change the
30    href value below to reflect the base path you are serving from.
31
32    The path provided below has to start and end with a slash &quot;/&quot; in order for
33    it to work correctly.
34
35    For more details:
36    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
37
38    This is a placeholder for base href that will be replaced by the value of
39    the `--base-href` argument provided to `flutter build`.
40  --&gt;
41  &lt;base href=&quot;$FLUTTER_BASE_HREF&quot;&gt;
42
43  &lt;meta charset=&quot;UTF-8&quot;&gt;
44  &lt;meta content=&quot;IE=Edge&quot; http-equiv=&quot;X-UA-Compatible&quot;&gt;
45  &lt;meta name=&quot;description&quot; content=&quot;A new Flutter project.&quot;&gt;
46
47  &lt;!-- iOS meta tags &amp; icons --&gt;
48  &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot;&gt;
49  &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot;&gt;
50  &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;flutter_application_1&quot;&gt;
51  &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;icons/Icon-192.png&quot;&gt;
52
53  &lt;title&gt;flutter_application_1&lt;/title&gt;
54  &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;
55&lt;/head&gt;
56&lt;body&gt;
57  
58  &lt;script&gt;
59    import { initializeApp } from &quot;firebase/app&quot;;
60    import { } from &quot;https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js&quot;
61    import { } from &quot;https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js&quot;
62// TODO: Add SDKs for Firebase products that you want to use
63// https://firebase.google.com/docs/web/setup#available-libraries
64
65// Your web app's Firebase configuration
66    const firebaseConfig = {
67      apiKey: &quot;...&quot;,
68      authDomain: &quot;...&quot;,
69      databaseURL: &quot;...&quot;,
70      projectId: &quot;...&quot;,
71      storageBucket: &quot;...&quot;,
72      messagingSenderId: &quot;...&quot;,
73      appId: &quot;...&quot;
74    };
75
76// Initialize Firebase
77const app = initializeApp(firebaseConfig);
78  // Initialize Firebase
79  firebase.initializeApp(firebaseConfig);
80    var serviceWorkerVersion = null;
81    var scriptLoaded = false;
82    function loadMainDartJs() {
83      if (scriptLoaded) {
84        return;
85      }
86      scriptLoaded = true;
87      var scriptTag = document.createElement('script');
88      scriptTag.src = 'main.dart.js';
89      scriptTag.type = 'application/javascript';
90      document.body.append(scriptTag);
91    }
92
93    if ('serviceWorker' in navigator) {
94      // Service workers are supported. Use them.
95      window.addEventListener('load', function () {
96        // Wait for registration to finish before dropping the &lt;script&gt; tag.
97        // Otherwise, the browser will load the script multiple times,
98        // potentially different versions.
99        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
100        navigator.serviceWorker.register(serviceWorkerUrl)
101          .then((reg) =&gt; {
102            function waitForActivation(serviceWorker) {
103              serviceWorker.addEventListener('statechange', () =&gt; {
104                if (serviceWorker.state == 'activated') {
105                  console.log('Installed new service worker.');
106                  loadMainDartJs();
107                }
108              });
109            }
110            if (!reg.active &amp;&amp; (reg.installing || reg.waiting)) {
111              // No active web worker and we have installed or are installing
112              // one for the first time. Simply wait for it to activate.
113              waitForActivation(reg.installing || reg.waiting);
114            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
115              // When the app updates the serviceWorkerVersion changes, so we
116              // need to ask the service worker to update.
117              console.log('New service worker available.');
118              reg.update();
119              waitForActivation(reg.installing);
120            } else {
121              // Existing service worker is still good.
122              console.log('Loading app from service worker.');
123              loadMainDartJs();
124            }
125          });
126
127        // If service worker doesn't succeed in a reasonable amount of time,
128        // fallback to plaint &lt;script&gt; tag.
129        setTimeout(() =&gt; {
130          if (!scriptLoaded) {
131            console.warn(
132              'Failed to load app from service worker. Falling back to plain &lt;script&gt; tag.',
133            );
134            loadMainDartJs();
135          }
136        }, 4000);
137      });
138    } else {
139      // Service workers not supported. Just drop the &lt;script&gt; tag.
140      loadMainDartJs();
141    }
142  &lt;/script&gt;
143&lt;/body&gt;
144&lt;/html&gt;
145import 'package:cloud_firestore/cloud_firestore.dart';
146import 'package:flutter/material.dart';
147import 'package:flutter_web_diary/diary_card.dart';
148import 'package:flutter_web_diary/diary_entry_model.dart';
149import 'package:flutter_web_diary/top_bar_title.dart';
150import 'package:provider/provider.dart';
151
152import 'diary_entry_page.dart';
153
154// Import the firebase_core plugin
155import 'package:firebase_core/firebase_core.dart';
156
157Future&lt;void&gt; main() async {
158  WidgetsFlutterBinding.ensureInitialized();
159  await Firebase.initializeApp();
160  runApp(MyApp());
161}
162
163/// We are using a StatefulWidget such that we only create the [Future] once,
164/// no matter how many times our widget rebuild.
165/// If we used a [StatelessWidget], in the event where [App] is rebuilt, that
166/// would re-initialize FlutterFire and make our application re-enter loading state,
167/// which is undesired.
168class App extends StatefulWidget {
169  // Create the initialization Future outside of `build`:
170  @override
171  _AppState createState() =&gt; _AppState();
172}
173
174class _AppState extends State&lt;App&gt; {
175  /// The future is part of the state of our widget. We should not call `initializeApp`
176  /// directly inside [build].
177  final Future&lt;FirebaseApp&gt; _initialization = Firebase.initializeApp();
178
179  @override
180  Widget build(BuildContext context) {
181    return FutureBuilder(
182      // Initialize FlutterFire:
183      future: _initialization,
184      builder: (context, snapshot) {
185        // Check for errors
186        if (snapshot.hasError) {
187          return Text(snapshot.error.toString());
188        }
189
190        // Once complete, show your application
191        if (snapshot.connectionState == ConnectionState.done) {
192          return MyApp();
193        }
194
195        // Otherwise, show something whilst waiting for initialization to complete
196        return CircularProgressIndicator();
197      },
198    );
199  }
200}
201
202class MyApp extends StatelessWidget {
203  @override
204  Widget build(BuildContext context) {
205    // Refer to https://firebase.flutter.dev
206
207    final diaryCollection = FirebaseFirestore.instance.collection('diaries');
208    final diaryStream = diaryCollection.snapshots().map((snapshot) {
209      return snapshot.docs.map((doc) =&gt; DiaryEntry.fromDoc(doc)).toList();
210    });
211    return StreamProvider&lt;List&lt;DiaryEntry&gt;&gt;(
212      create: (_) =&gt; diaryStream,
213      child: MaterialApp(
214        title: 'My Diary',
215        debugShowCheckedModeBanner: false,
216        theme: ThemeData(
217          colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.indigo).copyWith(secondary: Colors.pink),
218        ),
219        initialRoute: '/',
220        routes: {
221          '/': (context) =&gt; MyHomePage(),
222          '/new-entry': (context) =&gt; DiaryEntryPage.add(),
223        },
224      ),
225    );
226  }
227}
228
229class MyHomePage extends StatefulWidget {
230  MyHomePage({Key key, this.title}) : super(key: key);
231
232  final String title;
233
234  @override
235  _MyHomePageState createState() =&gt; _MyHomePageState();
236}
237
238class _MyHomePageState extends State&lt;MyHomePage&gt; {
239  @override
240  Widget build(BuildContext context) {
241    final diaryEntries = Provider.of&lt;List&lt;DiaryEntry&gt;&gt;(context);
242    return Scaffold(
243      appBar: AppBar(
244        bottom: PreferredSize(
245          preferredSize: Size.fromHeight(94.0),
246          child: TopBarTitle('Diary Entries'),
247        ),
248        elevation: 0,
249      ),
250      body: Center(
251        child: SizedBox(
252          width: MediaQuery.of(context).size.width * 3 / 5,
253          child: ListView(
254            children: &lt;Widget&gt;[
255              SizedBox(height: 40),
256              if (diaryEntries != null)
257                for (var diaryData in diaryEntries)
258                  DiaryCard(diaryEntry: diaryData),
259              if (diaryEntries == null)
260                Center(child: CircularProgressIndicator()),
261            ],
262          ),
263        ),
264      ),
265      floatingActionButtonLocation: FloatingActionButtonLocation.endTop,
266      floatingActionButton: FloatingActionButton(
267        elevation: 1.5,
268        onPressed: () =&gt; Navigator.of(context).pushNamed('/new-entry'),
269        tooltip: 'Add To Do',
270        child: Icon(Icons.add),
271        backgroundColor: Theme.of(context).colorScheme.secondary,
272      ),
273    );
274  }
275}
276

ANSWER

Answered 2021-Oct-23 at 21:55

For firebase in web there is a different package. Please check this one Firebase_core_web

Source https://stackoverflow.com/questions/69692070

QUESTION

Error when creating custom dashboard using WooCommerce REST API

Asked 2021-Oct-27 at 05:08

I am building a custom dashboard seen here: https://github.com/shahroznawaz/woo-dashboard

I am getting this error: Fatal error: Uncaught Error: Cannot use object of type stdClass as array in /Users/helloworld/Desktop/test/index.php:153 Stack trace: #0 {main} thrown in /Users/helloworld/Desktop/test/index.php on line 153

I have found another stackoverflow post with the same error which is unresolved here How Can I adjust my code to prevent the errors?

1&lt;?php
2require __DIR__ . '/vendor/autoload.php';
3
4use Automattic\WooCommerce\Client;
5use Automattic\WooCommerce\HttpClient\HttpClientException;
6$woocommerce = new Client(
7    'http://localhost:10053/', // Your store URL
8    'consumerkeyhere', // Your consumer key
9    'secretkeyhere', // Your consumer secret
10    [
11        'wp_api' =&gt; true, // Enable the WP REST API integration
12        'version' =&gt; 'wc/v2' // WooCommerce WP REST API version
13        
14    ]
15);
16
17//$products = $woocommerce-&gt;get('products');
18
19
20try {
21
22    $results = $woocommerce-&gt;get('orders');
23    $products = $woocommerce-&gt;get('products');
24    $customers = $woocommerce-&gt;get('customers');
25    $result = count($results);
26    $customer = count($customers);
27    $product = count($products);
28    $query = ['date_min' =&gt; '2017-10-01', 'date_max' =&gt; '2021-10-30'];
29    $sales = $woocommerce-&gt;get('reports/sales', $query);
30    $sale = $sales[0]-&gt;total_sales;
31
32    // Last request data.
33
34    $lastRequest = $woocommerce-&gt;http-&gt;getRequest();
35    $lastRequest-&gt;getUrl(); // Requested URL (string).
36    $lastRequest-&gt;getMethod(); // Request method (string).
37    $lastRequest-&gt;getParameters(); // Request parameters (array).
38    $lastRequest-&gt;getHeaders(); // Request headers (array).
39    $lastRequest-&gt;getBody(); // Request body (JSON).
40
41    // Last response data.
42
43    $lastResponse = $woocommerce-&gt;http-&gt;getResponse();
44    $lastResponse-&gt;getCode(); // Response code (int).
45    $lastResponse-&gt;getHeaders(); // Response headers (array).
46    $lastResponse-&gt;getBody(); // Response body (JSON).
47}
48
49catch(HttpClientException $e) {
50    $e-&gt;getMessage(); // Error message.
51    $e-&gt;getRequest(); // Last request data.
52    $e-&gt;getResponse(); // Last response data.
53}
54
55if (isset($_POST['btn-update'])) {
56    $status = $_POST['bookId'];
57    $st = $_POST['ostatus'];
58
59    $woocommerce-&gt;put('orders/' . $status, array(
60        'status' =&gt; $st
61    ));
62    header('Location: http://localhost:10053/');
63}
64
65
66if (isset($_POST['btn-delete'])) {
67    $oid = $_POST['cId'];
68
69    $woocommerce-&gt;delete('orders/' . $oid, ['force' =&gt; true]);
70    header('Location: http://localhost:10053/');
71}
72
73?&gt;
74
75
76&lt;!DOCTYPE html&gt;
77&lt;html lang=&quot;en&quot;&gt;
78
79&lt;head&gt;
80    &lt;meta charset=&quot;utf-8&quot;&gt;
81    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
82    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
83    &lt;!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --&gt;
84    &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
85    &lt;meta name=&quot;author&quot; content=&quot;&quot;&gt;
86    &lt;link rel=&quot;icon&quot; href=&quot;../../favicon.ico&quot;&gt;
87    &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js&quot;&gt;&lt;/script&gt;
88
89    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css&quot; /&gt;
90    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot; /&gt;
91
92    &lt;script src=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;
93
94    &lt;title&gt;Dashboard Template for Bootstrap&lt;/title&gt;
95
96&lt;/head&gt;
97    &lt;div class=&quot;container&quot;&gt;
98            &lt;div class=&quot;col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-1&quot;&gt;
99                     &lt;h1 class=&quot;page-header&quot;&gt;Dashboard&lt;/h1&gt;
100
101                     &lt;div class=&quot;row placeholders&quot;&gt;
102                                &lt;div class=&quot;col-xs-6 col-sm-3 placeholder&quot;&gt;
103                                    &lt;p id=&quot;large&quot;&gt;
104                                        &lt;?php echo $result?&gt;
105                                    &lt;/p&gt;
106                                    &lt;hr&gt;
107                                    &lt;span class=&quot;text-muted&quot;&gt;New Orders&lt;/span&gt;
108                                &lt;/div&gt;
109                                &lt;div class=&quot;col-xs-6 col-sm-3 placeholder&quot;&gt;
110                                    &lt;p id=&quot;large&quot;&gt;
111                                        &lt;?php echo $customer?&gt;
112                                    &lt;/p&gt;
113                                    &lt;hr&gt;
114
115                                    &lt;span class=&quot;text-muted&quot;&gt;Customers&lt;/span&gt;
116                                &lt;/div&gt;
117                                &lt;div class=&quot;col-xs-6 col-sm-3 placeholder&quot;&gt;
118                                    &lt;p id=&quot;large&quot;&gt;
119                                        &lt;?php echo $product?&gt;
120                                    &lt;/p&gt;
121                                    &lt;hr&gt;
122                                    &lt;span class=&quot;text-muted&quot;&gt;All Products&lt;/span&gt;
123                                &lt;/div&gt;
124                                &lt;div class=&quot;col-xs-6 col-sm-3 placeholder&quot;&gt;
125                                    &lt;p id=&quot;large&quot;&gt;
126                                        &lt;?php echo $sale?&gt;
127                                    &lt;/p&gt;
128                                    &lt;hr&gt;
129                                    &lt;span class=&quot;text-muted&quot;&gt;Total Sales&lt;/span&gt;
130                                &lt;/div&gt;
131                      &lt;/div&gt;
132              &lt;/div&gt;
133      &lt;/div&gt;
134             &lt;div class=&quot;container&quot;&gt;
135                              &lt;h2 class=&quot;sub-header&quot;&gt;Orders List&lt;/h2&gt;
136                                &lt;div class='table-responsive'&gt;
137                                    &lt;table id='myTable' class='table table-striped table-bordered'&gt;
138                                        &lt;thead&gt;
139                                            &lt;tr&gt;
140                                                &lt;th&gt;Order #&lt;/th&gt;
141                                                &lt;th&gt;Customer&lt;/th&gt;
142                                                &lt;th&gt;Address&lt;/th&gt;
143                                                &lt;th&gt;Contact&lt;/th&gt;
144                                                &lt;th&gt;Order Date&lt;/th&gt;
145                                                &lt;th&gt;Status&lt;/th&gt;
146                                                &lt;th&gt;Actions&lt;/th&gt;
147                                            &lt;/tr&gt;
148                                        &lt;/thead&gt;
149                                        &lt;tbody&gt;
150                                            &lt;?php foreach ($results as $details){
151
152                echo &quot;&lt;tr&gt;&lt;td&gt;&quot; . $details[&quot;id&quot;].&quot;&lt;/td&gt;
153                          &lt;td&gt;&quot; . $details[&quot;billing&quot;][&quot;first_name&quot;].$details[&quot;billing&quot;][&quot;last_name&quot;].&quot;&lt;/td&gt;
154                          &lt;td&gt;&quot; . $details[&quot;shipping&quot;][&quot;address_1&quot;].&quot;&lt;/td&gt;
155                          &lt;td&gt;&quot; . $details[&quot;billing&quot;][&quot;phone&quot;].&quot;&lt;/td&gt;
156                          &lt;td&gt;&quot; . $details[&quot;date_created&quot;].&quot;&lt;/td&gt;
157                          &lt;td&gt;&quot; . $details[&quot;status&quot;].&quot;&lt;/td&gt;
158                          &lt;td&gt;&lt;a class='open-AddBookDialog btn btn-primary' data-target='#myModal' data-id=&quot;.$details['id'].&quot; data-toggle='modal'&gt;Update&lt;/a&gt;
159                          &lt;a class='open-deleteDialog btn btn-danger' data-target='#myModal1' data-id=&quot;.$details['id'].&quot; data-toggle='modal'&gt;Delete&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&quot;;
160                }
161                ?&gt;
162                                        &lt;/tbody&gt;
163                                    &lt;/table&gt;
164                                &lt;/div&gt;
165               &lt;/div&gt;
166
167                &lt;div class=&quot;container&quot;&gt;
168                                    &lt;h2 class=&quot;sub-header&quot;&gt;Customers List&lt;/h2&gt;
169                                    &lt;div class='table-responsive'&gt;
170                                        &lt;table id='myTable' class='table table-striped table-bordered'&gt;
171                                            &lt;thead&gt;
172                                                &lt;tr&gt;
173                                                    &lt;th&gt;Email&lt;/th&gt;
174                                                    &lt;th&gt;Name&lt;/th&gt;
175                                                    &lt;th&gt;Billing Address&lt;/th&gt;
176                                                    &lt;th&gt;Total Orders&lt;/th&gt;
177                                                    &lt;th&gt;Total spent&lt;/th&gt;
178                                                    &lt;th&gt;Avatar&lt;/th&gt;
179                                                &lt;/tr&gt;
180                                            &lt;/thead&gt;
181                                            &lt;tbody&gt;
182                                                &lt;?php 
183                    foreach($customers as $customer){
184
185                    echo &quot;&lt;tr&gt;&lt;td&gt;&quot; . $customer[&quot;email&quot;].&quot;&lt;/td&gt;
186                              &lt;td&gt;&quot; . $customer[&quot;first_name&quot;].$customer[&quot;last_name&quot;].&quot;&lt;/td&gt;
187                              &lt;td&gt;&quot; . $customer[&quot;billing&quot;][&quot;address_1&quot;].&quot;&lt;/td&gt;
188                              &lt;td&gt;&quot; . $customer[&quot;orders_count&quot;].&quot;&lt;/td&gt;
189                              &lt;td&gt;&quot; . $customer[&quot;total_spent&quot;].&quot;&lt;/td&gt;
190                              &lt;td&gt;&lt;img height='50px' width='50px' src='&quot;.$customer[&quot;avatar_url&quot;].&quot;'&gt;&lt;/td&gt;&lt;/tr&gt;&quot;;
191                    }
192
193                    ?&gt;
194                                            &lt;/tbody&gt;
195                                        &lt;/table&gt;
196                                    &lt;/div&gt;
197    &lt;/div&gt;
198
199    &lt;div class=&quot;container&quot;&gt;
200                                    &lt;h2 class=&quot;sub-header&quot;&gt;Products List&lt;/h2&gt;
201                                    &lt;div class='table-responsive'&gt;
202                                        &lt;table id='myTable' class='table table-striped table-bordered'&gt;
203                                            &lt;thead&gt;
204                                                &lt;tr&gt;
205                                                    &lt;th&gt;SKU&lt;/th&gt;
206                                                    &lt;th&gt;Name&lt;/th&gt;
207                                                    &lt;th&gt;Status&lt;/th&gt;
208                                                    &lt;th&gt;Price&lt;/th&gt;
209                                                    &lt;th&gt;Total Sales&lt;/th&gt;
210                                                    &lt;th&gt;Picture&lt;/th&gt;
211                                                &lt;/tr&gt;
212                                            &lt;/thead&gt;
213                                            &lt;tbody&gt;
214                                                &lt;?php 
215                    foreach($products as $product){
216
217                    echo &quot;&lt;tr&gt;&lt;td&gt;&quot; . $product[&quot;sku&quot;].&quot;&lt;/td&gt;
218                              &lt;td&gt;&quot; . $product[&quot;name&quot;].&quot;&lt;/td&gt;
219                              &lt;td&gt;&quot; . $product[&quot;status&quot;].&quot;&lt;/td&gt;
220                              &lt;td&gt;&quot; . $product[&quot;price&quot;].&quot;&lt;/td&gt;
221                              &lt;td&gt;&quot; . $product[&quot;total_sales&quot;].&quot;&lt;/td&gt;
222                              &lt;td&gt;&lt;img height='50px' width='50px' src='&quot;.$product[&quot;images&quot;][0][&quot;src&quot;].&quot;'&gt;&lt;/td&gt;&lt;/tr&gt;&quot;;
223                    }
224
225                    ?&gt;
226                                            &lt;/tbody&gt;
227                                        &lt;/table&gt;
228                                    &lt;/div&gt;
229    &lt;/div&gt;
230
231  &lt;div class=&quot;modal fade&quot; id=&quot;myModal&quot; role=&quot;dialog&quot;&gt;
232    &lt;div class=&quot;modal-dialog&quot;&gt;
233
234        &lt;!-- Modal content--&gt;
235        &lt;div class=&quot;modal-content&quot;&gt;
236            &lt;div class=&quot;modal-header&quot;&gt;
237                &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot;&gt;&amp;times;&lt;/button&gt;
238                &lt;h4 class=&quot;modal-title&quot;&gt;Update Order Status&lt;/h4&gt;
239            &lt;/div&gt;
240            &lt;div class=&quot;modal-body&quot;&gt;
241                &lt;p&gt;Order ID:&lt;/p&gt;
242                &lt;form action=&quot;&quot; method=&quot;post&quot;&gt;
243                    &lt;div class=&quot;form-group&quot;&gt;
244                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;bookId&quot; id=&quot;bookId&quot; value=&quot;&quot;&gt;
245
246                        &lt;p for=&quot;sel1&quot;&gt;Select list (select one):&lt;/p&gt;
247                        &lt;select class=&quot;form-control&quot; id=&quot;status&quot; name=&quot;ostatus&quot;&gt;
248                            &lt;option&gt;Pending Payment&lt;/option&gt;
249                            &lt;option&gt;processing&lt;/option&gt;
250                            &lt;option&gt;On Hold&lt;/option&gt;
251                            &lt;option&gt;completed&lt;/option&gt;
252                            &lt;option&gt;Cancelled&lt;/option&gt;
253                            &lt;option&gt;Refunded&lt;/option&gt;
254                            &lt;option&gt;Failed&lt;/option&gt;
255                        &lt;/select&gt;
256
257                    &lt;/div&gt;
258
259                    &lt;div class=&quot;modal-footer&quot;&gt;
260                        &lt;button type=&quot;submit&quot; class=&quot;btn btn-block&quot; name=&quot;btn-update&quot;&gt;Update&lt;/button&gt;
261                    &lt;/div&gt;
262                &lt;/form&gt;
263            &lt;/div&gt;
264        &lt;/div&gt;
265    &lt;/div&gt;
266&lt;/div&gt;
267
268&lt;div class=&quot;modal fade&quot; id=&quot;myModal1&quot; role=&quot;dialog&quot;&gt;
269    &lt;div class=&quot;modal-dialog&quot;&gt;
270
271        &lt;!-- Modal content--&gt;
272        &lt;div class=&quot;modal-content&quot;&gt;
273            &lt;div class=&quot;modal-header&quot;&gt;
274                &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot;&gt;&amp;times;&lt;/button&gt;
275                &lt;h4 class=&quot;modal-title&quot;&gt;Confirm Order Deletion&lt;/h4&gt;
276            &lt;/div&gt;
277            &lt;div class=&quot;modal-body&quot;&gt;
278                &lt;p&gt;Really you want to delete order?&lt;/p&gt;
279                &lt;form action=&quot;&quot; method=&quot;post&quot;&gt;
280                    &lt;div class=&quot;form-group&quot;&gt;
281                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;cId&quot; id=&quot;cId&quot; value=&quot;&quot;&gt;
282                    &lt;/div&gt;
283
284                    &lt;div class=&quot;modal-footer&quot;&gt;
285                &lt;button type=&quot;button&quot; class=&quot;btn btn-default&quot; data-dismiss=&quot;modal&quot;&gt;Cancel&lt;/button&gt;
286                &lt;button type=&quot;submit&quot; class=&quot;btn btn-danger&quot; name=&quot;btn-delete&quot;&gt;Delete&lt;/button&gt;
287                   &lt;/div&gt;
288                &lt;/form&gt;
289            &lt;/div&gt;
290        &lt;/div&gt;
291    &lt;/div&gt;
292&lt;/div&gt;
293
294
295
296        &lt;script&gt;
297            $(document).on(&quot;click&quot;, &quot;.open-AddBookDialog&quot;, function() {
298                var myBookId = $(this).data('id');
299                $(&quot;.modal-body #bookId&quot;).val(myBookId);
300            });
301        &lt;/script&gt;
302
303        
304        &lt;script&gt;
305            $(document).on(&quot;click&quot;, &quot;.open-deleteDialog&quot;, function() {
306                var myBook = $(this).data('id');
307                $(&quot;.modal-body #cId&quot;).val(myBook);
308            });
309        &lt;/script&gt;
310
311
312&lt;/body&gt;
313
314&lt;/html&gt;
315

enter image description here

ANSWER

Answered 2021-Oct-22 at 07:53

Try $details->id instead of $details["id"], and so on

Source https://stackoverflow.com/questions/69671832

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Meta Tags

Tutorials and Learning Resources are not available at this moment for Meta Tags

Share this Page

share link

Get latest updates on Meta Tags