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
by kpumuk ruby
2467 MIT
Search Engine Optimization (SEO) for Ruby on Rails applications.
by artesaos php
2449 MIT
SEO Tools for Laravel
by mateodelnorte javascript
1608 MIT
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?
by ktquez javascript
962 MIT
Manager the meta information of the head tag, a simple and easy way
by troxler javascript
232 MIT
Set document title and meta tags with Vue.js
by prodeveloper php
181 MIT
Sharing to Social Networks for Laravel 5
by eusonlito javascript
152 MIT
HTML Meta Tags management package available for for Laravel 5.*
by mendersoftware python
127 NOASSERTION
Yocto Project meta layer for the Mender client
by davmixcool php
91 MIT
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
by area17 php
43 MIT
Laravel auto head tags
by BaseMax python
22 GPL-3.0
Solving Facebook interview questions.
by HashandSalt php
8
A plugin for generating SEO meta tags
by gabrieljaguiar python
7
An image meta-feature extractor for meta-learning tasks.
by Eshy10 ruby
4
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.
by hojabbr php
4
Laravel package to get all the meta data from a URL
by embed-me c
3 GPL-3.0
meta-layer for EBAZ4205
by muratgozel javascript
2 MIT
HTML document head management including meta tags, social media tags, icons and JSONLD expressions across devices.
by piyushsi javascript
2 MIT
A Node.js module to fetch HTML meta tags and custom meta tags from a remote URL.
Top Authors in Meta Tags
1
2 Libraries
8
2
1 Libraries
4
3
1 Libraries
7
4
1 Libraries
8
5
1 Libraries
2
6
1 Libraries
6
7
1 Libraries
2
8
1 Libraries
152
9
1 Libraries
38
10
1 Libraries
2
1
2 Libraries
8
2
1 Libraries
4
3
1 Libraries
7
4
1 Libraries
8
5
1 Libraries
2
6
1 Libraries
6
7
1 Libraries
2
8
1 Libraries
152
9
1 Libraries
38
10
1 Libraries
2
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:12On 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) => { });
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) => {
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, () => {
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 && 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) => { });
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) => {
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, () => {
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 && 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: () => import('./common/resetPassword/resetpassword.module').then(m => m.ResetpasswordModule)
119 },
120 {
121 path: 'Supplier',
122 component: Userapplayout2Component,
123 loadChildren: () => import('./supplier/supplier.module').then(m => m.SupplierModule),
124
125 },
126 {
127 path: 'User',
128 component: Userapplayout2Component,
129 loadChildren: () => import('./user/user.module').then(m => m.UserModule),
130
131 },
132 {
133 path: 'MarketPlace',
134 //component: UsersApplayoutComponent,
135 //component: AppHeaderLayoutComponent,
136 component: Userapplayout2Component,
137 loadChildren: () => import('./marketplace/marketplace.module').then(m => m.MarketplaceModule),
138 },
139 {
140 path: 'User/Agrements',
141 //component: AppLayoutComponent,
142 component: AppHeaderLayoutComponent,
143
144 loadChildren: () => import('./agrements/agrements.module').then(m => m.AgrementsModule)
145 },
146 {
147 path: 'HWUser',
148 //component: AppLayoutComponent,
149 component: AppHeaderLayoutComponent,
150 loadChildren: () => import('./HelpAndFAQ/helpQuestion.module').then(m => m.HelpQuestionModule)
151 },
152 {
153 path: 'Tradesman',
154 component: Userapplayout2Component,
155 loadChildren: () => import('./trademan/trademan.module').then(m => m.TrademanModule),
156 canActivate: [AuthGuardTradesmanService],
157 canActivateChild: [AuthGuardTradesmanService]
158 },
159 {
160 path: 'ContactUs',
161 //component: AppLayoutComponent,
162 component: AppHeaderLayoutComponent,
163 loadChildren: () => import('./contactUs/contactUs.module').then(m => m.ContactUsModule)
164 },
165 {
166 path: 'landing-page/liveleads',
167 //component: AppLayoutComponent,
168 component: AppHeaderLayoutComponent,
169 loadChildren: () => import('./landing-page/liveleads/liveleads.module').then(m => m.LiveleadsModule)
170 },
171 {
172 path: 'landing-page',
173 component: AppHeaderLayoutComponent,
174 loadChildren: () => import('./landing-page/landing-page.module').then(m => 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) => { });
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) => {
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, () => {
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 && 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: () => import('./common/resetPassword/resetpassword.module').then(m => m.ResetpasswordModule)
119 },
120 {
121 path: 'Supplier',
122 component: Userapplayout2Component,
123 loadChildren: () => import('./supplier/supplier.module').then(m => m.SupplierModule),
124
125 },
126 {
127 path: 'User',
128 component: Userapplayout2Component,
129 loadChildren: () => import('./user/user.module').then(m => m.UserModule),
130
131 },
132 {
133 path: 'MarketPlace',
134 //component: UsersApplayoutComponent,
135 //component: AppHeaderLayoutComponent,
136 component: Userapplayout2Component,
137 loadChildren: () => import('./marketplace/marketplace.module').then(m => m.MarketplaceModule),
138 },
139 {
140 path: 'User/Agrements',
141 //component: AppLayoutComponent,
142 component: AppHeaderLayoutComponent,
143
144 loadChildren: () => import('./agrements/agrements.module').then(m => m.AgrementsModule)
145 },
146 {
147 path: 'HWUser',
148 //component: AppLayoutComponent,
149 component: AppHeaderLayoutComponent,
150 loadChildren: () => import('./HelpAndFAQ/helpQuestion.module').then(m => m.HelpQuestionModule)
151 },
152 {
153 path: 'Tradesman',
154 component: Userapplayout2Component,
155 loadChildren: () => import('./trademan/trademan.module').then(m => m.TrademanModule),
156 canActivate: [AuthGuardTradesmanService],
157 canActivateChild: [AuthGuardTradesmanService]
158 },
159 {
160 path: 'ContactUs',
161 //component: AppLayoutComponent,
162 component: AppHeaderLayoutComponent,
163 loadChildren: () => import('./contactUs/contactUs.module').then(m => m.ContactUsModule)
164 },
165 {
166 path: 'landing-page/liveleads',
167 //component: AppLayoutComponent,
168 component: AppHeaderLayoutComponent,
169 loadChildren: () => import('./landing-page/liveleads/liveleads.module').then(m => m.LiveleadsModule)
170 },
171 {
172 path: 'landing-page',
173 component: AppHeaderLayoutComponent,
174 loadChildren: () => import('./landing-page/landing-page.module').then(m => 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<?xml version="1.0" encoding="utf-8"?>
212<configuration>
213 <location path="." inheritInChildApplications="false">
214 <system.webServer>
215 <handlers>
216 <add name="iisnode" path="main.js" verb="*" modules="iisnode"/>
217 </handlers>
218 <aspNetCore processPath="dotnet" arguments=".\HW.Web2.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
219
220<rewrite>
221 <rules>
222 <rule name="LogFile" patternSyntax="ECMAScript" stopProcessing="true">
223 <match url="iisnode"/>
224 </rule>
225
226 <rule name="StaticContent">
227 <action type="Rewrite" url="{{REQUEST_URI}}"/>
228 </rule>
229 <rule name="DynamicContent">
230 <conditions>
231 <add input="{{REQUEST_FILENAME}}" matchType="IsFile" negate="True"/>
232 </conditions>
233 <action type="Rewrite" url="main.js"/>
234 </rule>
235 </rules>
236 </rewrite>
237 <iisnode devErrorsEnabled="false"
238 debuggingEnabled="false"
239 loggingEnabled="false"
240 nodeProcessCommandLine="C:\Program Files\nodejs\node.exe" />
241
242 </system.webServer>
243 </location>
244</configuration>
245
ANSWER
Answered 2022-Mar-06 at 11:12There 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 fromDEVELOPMENT
toPRODUCTION
and run your application. In some cases the app behaves differently in either configuration (looks for themain.js
file in another location whenPRODUCTION
). 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 atClientApp/dist/main.js
. So I had to modifyangular.json
changing theprojects:ClientApp:architect:build:options:outputPath
todist
(see also)
- In my case the
- 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 yourSupplyData
delegate.SupplyData
is not aFunc<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) => { });
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) => {
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, () => {
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 && 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: () => import('./common/resetPassword/resetpassword.module').then(m => m.ResetpasswordModule)
119 },
120 {
121 path: 'Supplier',
122 component: Userapplayout2Component,
123 loadChildren: () => import('./supplier/supplier.module').then(m => m.SupplierModule),
124
125 },
126 {
127 path: 'User',
128 component: Userapplayout2Component,
129 loadChildren: () => import('./user/user.module').then(m => m.UserModule),
130
131 },
132 {
133 path: 'MarketPlace',
134 //component: UsersApplayoutComponent,
135 //component: AppHeaderLayoutComponent,
136 component: Userapplayout2Component,
137 loadChildren: () => import('./marketplace/marketplace.module').then(m => m.MarketplaceModule),
138 },
139 {
140 path: 'User/Agrements',
141 //component: AppLayoutComponent,
142 component: AppHeaderLayoutComponent,
143
144 loadChildren: () => import('./agrements/agrements.module').then(m => m.AgrementsModule)
145 },
146 {
147 path: 'HWUser',
148 //component: AppLayoutComponent,
149 component: AppHeaderLayoutComponent,
150 loadChildren: () => import('./HelpAndFAQ/helpQuestion.module').then(m => m.HelpQuestionModule)
151 },
152 {
153 path: 'Tradesman',
154 component: Userapplayout2Component,
155 loadChildren: () => import('./trademan/trademan.module').then(m => m.TrademanModule),
156 canActivate: [AuthGuardTradesmanService],
157 canActivateChild: [AuthGuardTradesmanService]
158 },
159 {
160 path: 'ContactUs',
161 //component: AppLayoutComponent,
162 component: AppHeaderLayoutComponent,
163 loadChildren: () => import('./contactUs/contactUs.module').then(m => m.ContactUsModule)
164 },
165 {
166 path: 'landing-page/liveleads',
167 //component: AppLayoutComponent,
168 component: AppHeaderLayoutComponent,
169 loadChildren: () => import('./landing-page/liveleads/liveleads.module').then(m => m.LiveleadsModule)
170 },
171 {
172 path: 'landing-page',
173 component: AppHeaderLayoutComponent,
174 loadChildren: () => import('./landing-page/landing-page.module').then(m => 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<?xml version="1.0" encoding="utf-8"?>
212<configuration>
213 <location path="." inheritInChildApplications="false">
214 <system.webServer>
215 <handlers>
216 <add name="iisnode" path="main.js" verb="*" modules="iisnode"/>
217 </handlers>
218 <aspNetCore processPath="dotnet" arguments=".\HW.Web2.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
219
220<rewrite>
221 <rules>
222 <rule name="LogFile" patternSyntax="ECMAScript" stopProcessing="true">
223 <match url="iisnode"/>
224 </rule>
225
226 <rule name="StaticContent">
227 <action type="Rewrite" url="{{REQUEST_URI}}"/>
228 </rule>
229 <rule name="DynamicContent">
230 <conditions>
231 <add input="{{REQUEST_FILENAME}}" matchType="IsFile" negate="True"/>
232 </conditions>
233 <action type="Rewrite" url="main.js"/>
234 </rule>
235 </rules>
236 </rewrite>
237 <iisnode devErrorsEnabled="false"
238 debuggingEnabled="false"
239 loggingEnabled="false"
240 nodeProcessCommandLine="C:\Program Files\nodejs\node.exe" />
241
242 </system.webServer>
243 </location>
244</configuration>
245options.SupplyData = async (context, data) => { ... };
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
.
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) => { });
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) => {
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, () => {
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 && 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: () => import('./common/resetPassword/resetpassword.module').then(m => m.ResetpasswordModule)
119 },
120 {
121 path: 'Supplier',
122 component: Userapplayout2Component,
123 loadChildren: () => import('./supplier/supplier.module').then(m => m.SupplierModule),
124
125 },
126 {
127 path: 'User',
128 component: Userapplayout2Component,
129 loadChildren: () => import('./user/user.module').then(m => m.UserModule),
130
131 },
132 {
133 path: 'MarketPlace',
134 //component: UsersApplayoutComponent,
135 //component: AppHeaderLayoutComponent,
136 component: Userapplayout2Component,
137 loadChildren: () => import('./marketplace/marketplace.module').then(m => m.MarketplaceModule),
138 },
139 {
140 path: 'User/Agrements',
141 //component: AppLayoutComponent,
142 component: AppHeaderLayoutComponent,
143
144 loadChildren: () => import('./agrements/agrements.module').then(m => m.AgrementsModule)
145 },
146 {
147 path: 'HWUser',
148 //component: AppLayoutComponent,
149 component: AppHeaderLayoutComponent,
150 loadChildren: () => import('./HelpAndFAQ/helpQuestion.module').then(m => m.HelpQuestionModule)
151 },
152 {
153 path: 'Tradesman',
154 component: Userapplayout2Component,
155 loadChildren: () => import('./trademan/trademan.module').then(m => m.TrademanModule),
156 canActivate: [AuthGuardTradesmanService],
157 canActivateChild: [AuthGuardTradesmanService]
158 },
159 {
160 path: 'ContactUs',
161 //component: AppLayoutComponent,
162 component: AppHeaderLayoutComponent,
163 loadChildren: () => import('./contactUs/contactUs.module').then(m => m.ContactUsModule)
164 },
165 {
166 path: 'landing-page/liveleads',
167 //component: AppLayoutComponent,
168 component: AppHeaderLayoutComponent,
169 loadChildren: () => import('./landing-page/liveleads/liveleads.module').then(m => m.LiveleadsModule)
170 },
171 {
172 path: 'landing-page',
173 component: AppHeaderLayoutComponent,
174 loadChildren: () => import('./landing-page/landing-page.module').then(m => 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<?xml version="1.0" encoding="utf-8"?>
212<configuration>
213 <location path="." inheritInChildApplications="false">
214 <system.webServer>
215 <handlers>
216 <add name="iisnode" path="main.js" verb="*" modules="iisnode"/>
217 </handlers>
218 <aspNetCore processPath="dotnet" arguments=".\HW.Web2.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
219
220<rewrite>
221 <rules>
222 <rule name="LogFile" patternSyntax="ECMAScript" stopProcessing="true">
223 <match url="iisnode"/>
224 </rule>
225
226 <rule name="StaticContent">
227 <action type="Rewrite" url="{{REQUEST_URI}}"/>
228 </rule>
229 <rule name="DynamicContent">
230 <conditions>
231 <add input="{{REQUEST_FILENAME}}" matchType="IsFile" negate="True"/>
232 </conditions>
233 <action type="Rewrite" url="main.js"/>
234 </rule>
235 </rules>
236 </rewrite>
237 <iisnode devErrorsEnabled="false"
238 debuggingEnabled="false"
239 loggingEnabled="false"
240 nodeProcessCommandLine="C:\Program Files\nodejs\node.exe" />
241
242 </system.webServer>
243 </location>
244</configuration>
245options.SupplyData = async (context, data) => { ... };
246<?xml version="1.0" encoding="utf-8"?>
247<configuration>
248 <location path="." inheritInChildApplications="false">
249 <system.webServer>
250 <modules runAllManagedModulesForAllRequests="false">
251 <remove name="WebDAVModule" />
252 </modules>
253 <rewrite>
254 <rules>
255 <rule name="NonWwwRedirection" stopProcessing="false">
256 <match url=".*" />
257 <conditions>
258 <add input="{HTTP_HOST}" pattern="^www.mintplayer.com$" />
259 </conditions>
260 <action type="Redirect" url="https://mintplayer.com/{R:0}" redirectType="Permanent" />
261 </rule>
262 </rules>
263 </rewrite>
264 <httpProtocol>
265 <customHeaders>
266 <remove name="X-Powered-By" />
267 </customHeaders>
268 </httpProtocol>
269 <security>
270 <requestFiltering allowDoubleEscaping="false">
271 <requestLimits maxAllowedContentLength="30000000" maxUrl="40960" maxQueryString="20480" />
272 </requestFiltering>
273 </security>
274 <handlers>
275 <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
276 </handlers>
277 <aspNetCore processPath="dotnet" arguments=".\MintPlayer.Web.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
278 </system.webServer>
279 </location>
280 <system.web>
281 <compilation tempDirectory="......" />
282 </system.web>
283</configuration>
284
QUESTION
Border on top bar on mobile safari
Asked 2022-Feb-19 at 08:55Iâ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.
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:03QUESTION
Adding onclick function in anchor tag which is not working
Asked 2022-Jan-27 at 06:58I 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<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2 pageEncoding="ISO-8859-1"%>
3<!DOCTYPE html>
4<html>
5<head>
6<!-- Required meta tags -->
7<meta charset="utf-8">
8<meta name="viewport" content="width=device-width, initial-scale=1">
9
10<!-- Bootstrap CSS -->
11<link
12 href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
13 rel="stylesheet"
14 integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
15 crossorigin="anonymous">
16
17<title>Mole Calculator | Chemistry Calculator</title>
18
19</head>
20
21
22
23<body>
24
25 <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">
26
27 <div class="container-fluid">
28 <a class="navbar-brand" href="#"><h4>
29 <b>Chemistry Calculator</b>
30 </h4></a>
31
32 <button class="navbar-toggler" type="button"
33 data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
34 aria-controls="navbarSupportedContent" aria-expanded="false"
35 aria-label="Toggle navigation">
36 <span class="navbar-toggler-icon"></span>
37 </button>
38
39 <div class="collapse navbar-collapse" id="navbarSupportedContent">
40
41 <ul class="navbar-nav text-uppercase">
42
43 <li class="nav-item"><a class="nav-link active"
44 aria-current="page" href="/Chemistry-Calculator/">Home</a></li>
45
46 <li class="nav-item"><a class="nav-link active"
47 aria-current="page" href="/Chemistry-Calculator/about">About</a></li>
48
49
50 </ul>
51
52 </div>
53 </div>
54 </nav>
55
56 <div class="container" style="padding-top: 5%;">
57
58 <div class="card px-4 py-5" style="width: 650px;">
59 <div class="card-block">
60
61 <form action="/Chemistry-Calculator/Number-Of-Moles">
62
63 <div class="mb-3">
64 <label for="givenMass" class="form-label">Given Mass of
65 Substance</label> <input type="text" class="form-control" id="givenMass"
66 aria-describedby="emailHelp" name="givenMass"
67 value="${givenMass}" style="width: 600px">
68 </div>
69 <div class="mb-3">
70 <label for="molarMass" class="form-label">Molar Mass</label> <input
71 type="text" class="form-control" id="molarMass" name="molarMass"
72 value="${molarMass}" style="width: 600px">
73 </div>
74
75 <div class="mb-3">
76 <label for="molarMass" class="form-label">Moles</label> <input
77 type="text" class="form-control"
78 id="molarMass" name="moles" value="${moles}" style="width: 600px">
79 </div>
80
81 <input class="btn btn-outline-success" type="submit"
82 value="Calculate">
83
84 <div class="btn-group">
85 <button type="button" class="btn btn-success dropdown-toggle"
86 data-bs-toggle="dropdown" aria-expanded="false">Choose what to calculate </button>
87 <ul class="dropdown-menu">
88 <li><a class="dropdown-item" onclick="readonlyForMoles()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Moles</a></li>
89 <li><a class="dropdown-item" onclick="readonlyForMolarMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Molar Mass</a></li>
90 <li><a class="dropdown-item" onclick="readonlyForGivenMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Given mass</a></li>
91 </ul>
92 </div>
93
94 </form>
95 </div>
96 </div>
97 </div>
98
99 <script
100 src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
101 integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
102 crossorigin="anonymous"></script>
103 <script type="text/javascript" src="../javascript/script.js"></script>
104
105</body>
106</html>
107
My Java Script File:
1<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2 pageEncoding="ISO-8859-1"%>
3<!DOCTYPE html>
4<html>
5<head>
6<!-- Required meta tags -->
7<meta charset="utf-8">
8<meta name="viewport" content="width=device-width, initial-scale=1">
9
10<!-- Bootstrap CSS -->
11<link
12 href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
13 rel="stylesheet"
14 integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
15 crossorigin="anonymous">
16
17<title>Mole Calculator | Chemistry Calculator</title>
18
19</head>
20
21
22
23<body>
24
25 <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">
26
27 <div class="container-fluid">
28 <a class="navbar-brand" href="#"><h4>
29 <b>Chemistry Calculator</b>
30 </h4></a>
31
32 <button class="navbar-toggler" type="button"
33 data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
34 aria-controls="navbarSupportedContent" aria-expanded="false"
35 aria-label="Toggle navigation">
36 <span class="navbar-toggler-icon"></span>
37 </button>
38
39 <div class="collapse navbar-collapse" id="navbarSupportedContent">
40
41 <ul class="navbar-nav text-uppercase">
42
43 <li class="nav-item"><a class="nav-link active"
44 aria-current="page" href="/Chemistry-Calculator/">Home</a></li>
45
46 <li class="nav-item"><a class="nav-link active"
47 aria-current="page" href="/Chemistry-Calculator/about">About</a></li>
48
49
50 </ul>
51
52 </div>
53 </div>
54 </nav>
55
56 <div class="container" style="padding-top: 5%;">
57
58 <div class="card px-4 py-5" style="width: 650px;">
59 <div class="card-block">
60
61 <form action="/Chemistry-Calculator/Number-Of-Moles">
62
63 <div class="mb-3">
64 <label for="givenMass" class="form-label">Given Mass of
65 Substance</label> <input type="text" class="form-control" id="givenMass"
66 aria-describedby="emailHelp" name="givenMass"
67 value="${givenMass}" style="width: 600px">
68 </div>
69 <div class="mb-3">
70 <label for="molarMass" class="form-label">Molar Mass</label> <input
71 type="text" class="form-control" id="molarMass" name="molarMass"
72 value="${molarMass}" style="width: 600px">
73 </div>
74
75 <div class="mb-3">
76 <label for="molarMass" class="form-label">Moles</label> <input
77 type="text" class="form-control"
78 id="molarMass" name="moles" value="${moles}" style="width: 600px">
79 </div>
80
81 <input class="btn btn-outline-success" type="submit"
82 value="Calculate">
83
84 <div class="btn-group">
85 <button type="button" class="btn btn-success dropdown-toggle"
86 data-bs-toggle="dropdown" aria-expanded="false">Choose what to calculate </button>
87 <ul class="dropdown-menu">
88 <li><a class="dropdown-item" onclick="readonlyForMoles()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Moles</a></li>
89 <li><a class="dropdown-item" onclick="readonlyForMolarMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Molar Mass</a></li>
90 <li><a class="dropdown-item" onclick="readonlyForGivenMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Given mass</a></li>
91 </ul>
92 </div>
93
94 </form>
95 </div>
96 </div>
97 </div>
98
99 <script
100 src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
101 integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
102 crossorigin="anonymous"></script>
103 <script type="text/javascript" src="../javascript/script.js"></script>
104
105</body>
106</html>
107function readonlyForGivenMass() {
108 var x = document.getElementById("givenMass").readOnly;
109
110}
111
112function readonlyForMolarMass() {
113 var x = document.getElementById("molarMass").readOnly;
114
115}
116
117
118
119 function readonlyForMoles() {
120 var x = document.getElementById("moles").readOnly;
121
122
123}
124
ANSWER
Answered 2022-Jan-27 at 06:581<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2 pageEncoding="ISO-8859-1"%>
3<!DOCTYPE html>
4<html>
5<head>
6<!-- Required meta tags -->
7<meta charset="utf-8">
8<meta name="viewport" content="width=device-width, initial-scale=1">
9
10<!-- Bootstrap CSS -->
11<link
12 href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
13 rel="stylesheet"
14 integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
15 crossorigin="anonymous">
16
17<title>Mole Calculator | Chemistry Calculator</title>
18
19</head>
20
21
22
23<body>
24
25 <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">
26
27 <div class="container-fluid">
28 <a class="navbar-brand" href="#"><h4>
29 <b>Chemistry Calculator</b>
30 </h4></a>
31
32 <button class="navbar-toggler" type="button"
33 data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
34 aria-controls="navbarSupportedContent" aria-expanded="false"
35 aria-label="Toggle navigation">
36 <span class="navbar-toggler-icon"></span>
37 </button>
38
39 <div class="collapse navbar-collapse" id="navbarSupportedContent">
40
41 <ul class="navbar-nav text-uppercase">
42
43 <li class="nav-item"><a class="nav-link active"
44 aria-current="page" href="/Chemistry-Calculator/">Home</a></li>
45
46 <li class="nav-item"><a class="nav-link active"
47 aria-current="page" href="/Chemistry-Calculator/about">About</a></li>
48
49
50 </ul>
51
52 </div>
53 </div>
54 </nav>
55
56 <div class="container" style="padding-top: 5%;">
57
58 <div class="card px-4 py-5" style="width: 650px;">
59 <div class="card-block">
60
61 <form action="/Chemistry-Calculator/Number-Of-Moles">
62
63 <div class="mb-3">
64 <label for="givenMass" class="form-label">Given Mass of
65 Substance</label> <input type="text" class="form-control" id="givenMass"
66 aria-describedby="emailHelp" name="givenMass"
67 value="${givenMass}" style="width: 600px">
68 </div>
69 <div class="mb-3">
70 <label for="molarMass" class="form-label">Molar Mass</label> <input
71 type="text" class="form-control" id="molarMass" name="molarMass"
72 value="${molarMass}" style="width: 600px">
73 </div>
74
75 <div class="mb-3">
76 <label for="molarMass" class="form-label">Moles</label> <input
77 type="text" class="form-control"
78 id="molarMass" name="moles" value="${moles}" style="width: 600px">
79 </div>
80
81 <input class="btn btn-outline-success" type="submit"
82 value="Calculate">
83
84 <div class="btn-group">
85 <button type="button" class="btn btn-success dropdown-toggle"
86 data-bs-toggle="dropdown" aria-expanded="false">Choose what to calculate </button>
87 <ul class="dropdown-menu">
88 <li><a class="dropdown-item" onclick="readonlyForMoles()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Moles</a></li>
89 <li><a class="dropdown-item" onclick="readonlyForMolarMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Molar Mass</a></li>
90 <li><a class="dropdown-item" onclick="readonlyForGivenMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Given mass</a></li>
91 </ul>
92 </div>
93
94 </form>
95 </div>
96 </div>
97 </div>
98
99 <script
100 src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
101 integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
102 crossorigin="anonymous"></script>
103 <script type="text/javascript" src="../javascript/script.js"></script>
104
105</body>
106</html>
107function readonlyForGivenMass() {
108 var x = document.getElementById("givenMass").readOnly;
109
110}
111
112function readonlyForMolarMass() {
113 var x = document.getElementById("molarMass").readOnly;
114
115}
116
117
118
119 function readonlyForMoles() {
120 var x = document.getElementById("moles").readOnly;
121
122
123}
124<!DOCTYPE html>
125<html>
126<head>
127<!-- Required meta tags -->
128<meta charset="utf-8">
129<meta name="viewport" content="width=device-width, initial-scale=1">
130
131<!-- Bootstrap CSS -->
132<link
133 href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
134 rel="stylesheet"
135 integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
136 crossorigin="anonymous">
137
138<title>Mole Calculator | Chemistry Calculator</title>
139
140</head>
141
142
143
144<body>
145
146 <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">
147
148 <div class="container-fluid">
149 <a class="navbar-brand" href="#"><h4>
150 <b>Chemistry Calculator</b>
151 </h4></a>
152
153 <button class="navbar-toggler" type="button"
154 data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
155 aria-controls="navbarSupportedContent" aria-expanded="false"
156 aria-label="Toggle navigation">
157 <span class="navbar-toggler-icon"></span>
158 </button>
159
160 <div class="collapse navbar-collapse" id="navbarSupportedContent">
161
162 <ul class="navbar-nav text-uppercase">
163
164 <li class="nav-item"><a class="nav-link active"
165 aria-current="page" href="/Chemistry-Calculator/">Home</a></li>
166
167 <li class="nav-item"><a class="nav-link active"
168 aria-current="page" href="/Chemistry-Calculator/about">About</a></li>
169
170
171 </ul>
172
173 </div>
174 </div>
175 </nav>
176
177 <div class="container" style="padding-top: 5%;">
178
179 <div class="card px-4 py-5" style="width: 650px;">
180 <div class="card-block">
181
182 <form action="/Chemistry-Calculator/Number-Of-Moles">
183
184 <div class="mb-3">
185 <label for="givenMass" class="form-label">Given Mass of
186 Substance</label> <input type="text" class="form-control" id="givenMass"
187 aria-describedby="emailHelp" name="givenMass"
188 value="${givenMass}" style="width: 600px">
189 </div>
190 <div class="mb-3">
191 <label for="molarMass" class="form-label">Molar Mass</label> <input
192 type="text" class="form-control" id="moles" name="molarMass"
193 value="${molarMass}" style="width: 600px">
194 </div>
195
196 <div class="mb-3">
197 <label for="molarMass" class="form-label">Moles</label> <input
198 type="text" class="form-control"
199 id="molarMass" name="moles" value="${moles}" style="width: 600px">
200 </div>
201
202 <input class="btn btn-outline-success" type="submit"
203 value="Calculate">
204
205 <div class="btn-group">
206 <button type="button" class="btn btn-success dropdown-toggle"
207 data-bs-toggle="dropdown" aria-expanded="false">Choose what to calculate </button>
208 <ul class="dropdown-menu">
209 <li><a class="dropdown-item" onclick="readonlyForMoles(event)" href="/Chemistry-Calculator/Mole-Calculator">Calculate Moles</a></li>
210 <li><a class="dropdown-item" onclick="readonlyForMolarMass(event)" href="/Chemistry-Calculator/Mole-Calculator">Calculate Molar Mass</a></li>
211 <li><a class="dropdown-item" onclick="readonlyForGivenMass(event)" href="/Chemistry-Calculator/Mole-Calculator">Calculate Given mass</a></li>
212 </ul>
213 </div>
214
215 </form>
216 </div>
217 </div>
218 </div>
219
220 <script
221 src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
222 integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
223 crossorigin="anonymous"></script>
224
225 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
226 <script>
227 function readonlyForGivenMass(event) {
228 event.preventDefault()
229
230 var x = document.getElementById("moles").readOnly= false;
231 var x = document.getElementById("givenMass").readOnly= true;
232 var x = document.getElementById("molarMass").readOnly= false;
233
234}
235
236function readonlyForMolarMass(event) {
237 event.preventDefault()
238 var x = document.getElementById("molarMass").readOnly = true;
239 var x = document.getElementById("moles").readOnly= false;
240 var x = document.getElementById("givenMass").readOnly= false;
241
242}
243
244
245
246 function readonlyForMoles(event) {
247 event.preventDefault()
248var x = document.getElementById("molarMass").readOnly = false;
249 var x = document.getElementById("moles").readOnly = true;
250 var x = document.getElementById("givenMass").readOnly= false;
251
252
253}
254
255 </script>
256
257</body>
258</html>
259
if you want means you can remove event.preventDefault in each function and I hope this code will works for you. Thank you
QUESTION
images not appear in the blade page if send it to email by using queue job Laravel?
Asked 2022-Jan-16 at 02:42I 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
image'URL if I sent it without using queue job:
http://localhost:8000/assets/img/logo.png
The Blade Page
1 <!doctype html>
2<html lang="en"><head>
3 <!-- Required meta tags -->
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6
7 <link rel="stylesheet" href="{{asset('assets/css/bootstrap.css')}}">
8 <style type="text/css">
9 @import url({{asset('assets/css/style.css')}});
10
11 body {
12
13}
14 </style>
15 <title>login Page</title>
16 </head>
17<body>
18<section class="row">
19 <div class="col col-sm ">
20 </div>
21 <div class="col col-sm ml-5 pl-5" id="col1" >
22 <div class="container">
23 <div class="row mt-5 pl-5 mb-5 pb-5">
24 <img src="{{asset('assets/img/logo.png')}}" width="80" height="80" alt=""/>
25 </div>
26 <div class="row mt-5 mb-5 pb-5 ">
27 <img src="{{asset('assets/img/Sign in ~ Register Illustration.png')}}" width="263" height="241" alt=""/>
28 </div>
29 <h1>Hello, </h1>
30 <h2>Verification Code </h2>
31 <div class="row mt-5 mb-5 pb-5 pr-5">
32 <p class="font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted" id="text1">1Me will Keep your Contacts Secured in our Data base</p>
33 </div>
34
35 </div>
36
37 </div>
38 </section>
39<script src="{{asset('js/bootstrap.js')}}"></script>
40
41</body>
42</html>
43
Route:
1 <!doctype html>
2<html lang="en"><head>
3 <!-- Required meta tags -->
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6
7 <link rel="stylesheet" href="{{asset('assets/css/bootstrap.css')}}">
8 <style type="text/css">
9 @import url({{asset('assets/css/style.css')}});
10
11 body {
12
13}
14 </style>
15 <title>login Page</title>
16 </head>
17<body>
18<section class="row">
19 <div class="col col-sm ">
20 </div>
21 <div class="col col-sm ml-5 pl-5" id="col1" >
22 <div class="container">
23 <div class="row mt-5 pl-5 mb-5 pb-5">
24 <img src="{{asset('assets/img/logo.png')}}" width="80" height="80" alt=""/>
25 </div>
26 <div class="row mt-5 mb-5 pb-5 ">
27 <img src="{{asset('assets/img/Sign in ~ Register Illustration.png')}}" width="263" height="241" alt=""/>
28 </div>
29 <h1>Hello, </h1>
30 <h2>Verification Code </h2>
31 <div class="row mt-5 mb-5 pb-5 pr-5">
32 <p class="font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted" id="text1">1Me will Keep your Contacts Secured in our Data base</p>
33 </div>
34
35 </div>
36
37 </div>
38 </section>
39<script src="{{asset('js/bootstrap.js')}}"></script>
40
41</body>
42</html>
43 Route::group(['middleware'=>'guest:web'], function(){
44 Route::get('/register', [registerController::class,'register'])->name('site.register');
45 Route::match(['get','post'],'/register-create', [registerController::class,'create'])->name('site.register.create');
46});
47
Controller:
1 <!doctype html>
2<html lang="en"><head>
3 <!-- Required meta tags -->
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6
7 <link rel="stylesheet" href="{{asset('assets/css/bootstrap.css')}}">
8 <style type="text/css">
9 @import url({{asset('assets/css/style.css')}});
10
11 body {
12
13}
14 </style>
15 <title>login Page</title>
16 </head>
17<body>
18<section class="row">
19 <div class="col col-sm ">
20 </div>
21 <div class="col col-sm ml-5 pl-5" id="col1" >
22 <div class="container">
23 <div class="row mt-5 pl-5 mb-5 pb-5">
24 <img src="{{asset('assets/img/logo.png')}}" width="80" height="80" alt=""/>
25 </div>
26 <div class="row mt-5 mb-5 pb-5 ">
27 <img src="{{asset('assets/img/Sign in ~ Register Illustration.png')}}" width="263" height="241" alt=""/>
28 </div>
29 <h1>Hello, </h1>
30 <h2>Verification Code </h2>
31 <div class="row mt-5 mb-5 pb-5 pr-5">
32 <p class="font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted" id="text1">1Me will Keep your Contacts Secured in our Data base</p>
33 </div>
34
35 </div>
36
37 </div>
38 </section>
39<script src="{{asset('js/bootstrap.js')}}"></script>
40
41</body>
42</html>
43 Route::group(['middleware'=>'guest:web'], function(){
44 Route::get('/register', [registerController::class,'register'])->name('site.register');
45 Route::match(['get','post'],'/register-create', [registerController::class,'create'])->name('site.register.create');
46});
47 public function create(RegisterRequest $request)
48{
49 $user = User::create([
50 'firstName' => $request->firstName,
51 'middleName' => $request->middleName,
52 'lastName' => $request->lastName,
53 'email' => $request->email,
54 'password' => Hash::make($request->password),
55 ]);
56 $on = \Carbon\Carbon::now()->addSecond(10);
57 dispatch(new VerifyEmailJob($user))->delay($on);
58 return redirect()->route('landingPage')->with(['success'=>'We sent verifying email check it']);
59}
60
queue job:
1 <!doctype html>
2<html lang="en"><head>
3 <!-- Required meta tags -->
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6
7 <link rel="stylesheet" href="{{asset('assets/css/bootstrap.css')}}">
8 <style type="text/css">
9 @import url({{asset('assets/css/style.css')}});
10
11 body {
12
13}
14 </style>
15 <title>login Page</title>
16 </head>
17<body>
18<section class="row">
19 <div class="col col-sm ">
20 </div>
21 <div class="col col-sm ml-5 pl-5" id="col1" >
22 <div class="container">
23 <div class="row mt-5 pl-5 mb-5 pb-5">
24 <img src="{{asset('assets/img/logo.png')}}" width="80" height="80" alt=""/>
25 </div>
26 <div class="row mt-5 mb-5 pb-5 ">
27 <img src="{{asset('assets/img/Sign in ~ Register Illustration.png')}}" width="263" height="241" alt=""/>
28 </div>
29 <h1>Hello, </h1>
30 <h2>Verification Code </h2>
31 <div class="row mt-5 mb-5 pb-5 pr-5">
32 <p class="font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted" id="text1">1Me will Keep your Contacts Secured in our Data base</p>
33 </div>
34
35 </div>
36
37 </div>
38 </section>
39<script src="{{asset('js/bootstrap.js')}}"></script>
40
41</body>
42</html>
43 Route::group(['middleware'=>'guest:web'], function(){
44 Route::get('/register', [registerController::class,'register'])->name('site.register');
45 Route::match(['get','post'],'/register-create', [registerController::class,'create'])->name('site.register.create');
46});
47 public function create(RegisterRequest $request)
48{
49 $user = User::create([
50 'firstName' => $request->firstName,
51 'middleName' => $request->middleName,
52 'lastName' => $request->lastName,
53 'email' => $request->email,
54 'password' => Hash::make($request->password),
55 ]);
56 $on = \Carbon\Carbon::now()->addSecond(10);
57 dispatch(new VerifyEmailJob($user))->delay($on);
58 return redirect()->route('landingPage')->with(['success'=>'We sent verifying email check it']);
59}
60 <?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->user= $user;
85 }
86
87 /**
88 * Execute the job.
89 *
90 * @return void
91 */
92 public function handle()
93 {
94 Mail::to($this->user->email)->send(new VerifyEmail($this->user));
95
96 }
97}
98
Mail class:
1 <!doctype html>
2<html lang="en"><head>
3 <!-- Required meta tags -->
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6
7 <link rel="stylesheet" href="{{asset('assets/css/bootstrap.css')}}">
8 <style type="text/css">
9 @import url({{asset('assets/css/style.css')}});
10
11 body {
12
13}
14 </style>
15 <title>login Page</title>
16 </head>
17<body>
18<section class="row">
19 <div class="col col-sm ">
20 </div>
21 <div class="col col-sm ml-5 pl-5" id="col1" >
22 <div class="container">
23 <div class="row mt-5 pl-5 mb-5 pb-5">
24 <img src="{{asset('assets/img/logo.png')}}" width="80" height="80" alt=""/>
25 </div>
26 <div class="row mt-5 mb-5 pb-5 ">
27 <img src="{{asset('assets/img/Sign in ~ Register Illustration.png')}}" width="263" height="241" alt=""/>
28 </div>
29 <h1>Hello, </h1>
30 <h2>Verification Code </h2>
31 <div class="row mt-5 mb-5 pb-5 pr-5">
32 <p class="font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted" id="text1">1Me will Keep your Contacts Secured in our Data base</p>
33 </div>
34
35 </div>
36
37 </div>
38 </section>
39<script src="{{asset('js/bootstrap.js')}}"></script>
40
41</body>
42</html>
43 Route::group(['middleware'=>'guest:web'], function(){
44 Route::get('/register', [registerController::class,'register'])->name('site.register');
45 Route::match(['get','post'],'/register-create', [registerController::class,'create'])->name('site.register.create');
46});
47 public function create(RegisterRequest $request)
48{
49 $user = User::create([
50 'firstName' => $request->firstName,
51 'middleName' => $request->middleName,
52 'lastName' => $request->lastName,
53 'email' => $request->email,
54 'password' => Hash::make($request->password),
55 ]);
56 $on = \Carbon\Carbon::now()->addSecond(10);
57 dispatch(new VerifyEmailJob($user))->delay($on);
58 return redirect()->route('landingPage')->with(['success'=>'We sent verifying email check it']);
59}
60 <?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->user= $user;
85 }
86
87 /**
88 * Execute the job.
89 *
90 * @return void
91 */
92 public function handle()
93 {
94 Mail::to($this->user->email)->send(new VerifyEmail($this->user));
95
96 }
97}
98 <?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->user = $user;
120 }
121 /**
122 * Build the message.
123 *
124 * @return $this
125 */
126 public function build()
127 {
128 $user = $this->user;
129 return $this->subject('Mail from Oneme')
130 ->view('site.auth.verifyEmail',compact('user'));
131 }
132}
133
Any Help
ANSWER
Answered 2022-Jan-16 at 02:42I 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 <!doctype html>
2<html lang="en"><head>
3 <!-- Required meta tags -->
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6
7 <link rel="stylesheet" href="{{asset('assets/css/bootstrap.css')}}">
8 <style type="text/css">
9 @import url({{asset('assets/css/style.css')}});
10
11 body {
12
13}
14 </style>
15 <title>login Page</title>
16 </head>
17<body>
18<section class="row">
19 <div class="col col-sm ">
20 </div>
21 <div class="col col-sm ml-5 pl-5" id="col1" >
22 <div class="container">
23 <div class="row mt-5 pl-5 mb-5 pb-5">
24 <img src="{{asset('assets/img/logo.png')}}" width="80" height="80" alt=""/>
25 </div>
26 <div class="row mt-5 mb-5 pb-5 ">
27 <img src="{{asset('assets/img/Sign in ~ Register Illustration.png')}}" width="263" height="241" alt=""/>
28 </div>
29 <h1>Hello, </h1>
30 <h2>Verification Code </h2>
31 <div class="row mt-5 mb-5 pb-5 pr-5">
32 <p class="font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted" id="text1">1Me will Keep your Contacts Secured in our Data base</p>
33 </div>
34
35 </div>
36
37 </div>
38 </section>
39<script src="{{asset('js/bootstrap.js')}}"></script>
40
41</body>
42</html>
43 Route::group(['middleware'=>'guest:web'], function(){
44 Route::get('/register', [registerController::class,'register'])->name('site.register');
45 Route::match(['get','post'],'/register-create', [registerController::class,'create'])->name('site.register.create');
46});
47 public function create(RegisterRequest $request)
48{
49 $user = User::create([
50 'firstName' => $request->firstName,
51 'middleName' => $request->middleName,
52 'lastName' => $request->lastName,
53 'email' => $request->email,
54 'password' => Hash::make($request->password),
55 ]);
56 $on = \Carbon\Carbon::now()->addSecond(10);
57 dispatch(new VerifyEmailJob($user))->delay($on);
58 return redirect()->route('landingPage')->with(['success'=>'We sent verifying email check it']);
59}
60 <?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->user= $user;
85 }
86
87 /**
88 * Execute the job.
89 *
90 * @return void
91 */
92 public function handle()
93 {
94 Mail::to($this->user->email)->send(new VerifyEmail($this->user));
95
96 }
97}
98 <?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->user = $user;
120 }
121 /**
122 * Build the message.
123 *
124 * @return $this
125 */
126 public function build()
127 {
128 $user = $this->user;
129 return $this->subject('Mail from Oneme')
130 ->view('site.auth.verifyEmail',compact('user'));
131 }
132}
133APP_URL = "https://example.com" #change this with your application url
134
The on the view file, I'd do something like
1 <!doctype html>
2<html lang="en"><head>
3 <!-- Required meta tags -->
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6
7 <link rel="stylesheet" href="{{asset('assets/css/bootstrap.css')}}">
8 <style type="text/css">
9 @import url({{asset('assets/css/style.css')}});
10
11 body {
12
13}
14 </style>
15 <title>login Page</title>
16 </head>
17<body>
18<section class="row">
19 <div class="col col-sm ">
20 </div>
21 <div class="col col-sm ml-5 pl-5" id="col1" >
22 <div class="container">
23 <div class="row mt-5 pl-5 mb-5 pb-5">
24 <img src="{{asset('assets/img/logo.png')}}" width="80" height="80" alt=""/>
25 </div>
26 <div class="row mt-5 mb-5 pb-5 ">
27 <img src="{{asset('assets/img/Sign in ~ Register Illustration.png')}}" width="263" height="241" alt=""/>
28 </div>
29 <h1>Hello, </h1>
30 <h2>Verification Code </h2>
31 <div class="row mt-5 mb-5 pb-5 pr-5">
32 <p class="font-style-normall font-size-18 line-spacing-33 font-family-cairo text-muted" id="text1">1Me will Keep your Contacts Secured in our Data base</p>
33 </div>
34
35 </div>
36
37 </div>
38 </section>
39<script src="{{asset('js/bootstrap.js')}}"></script>
40
41</body>
42</html>
43 Route::group(['middleware'=>'guest:web'], function(){
44 Route::get('/register', [registerController::class,'register'])->name('site.register');
45 Route::match(['get','post'],'/register-create', [registerController::class,'create'])->name('site.register.create');
46});
47 public function create(RegisterRequest $request)
48{
49 $user = User::create([
50 'firstName' => $request->firstName,
51 'middleName' => $request->middleName,
52 'lastName' => $request->lastName,
53 'email' => $request->email,
54 'password' => Hash::make($request->password),
55 ]);
56 $on = \Carbon\Carbon::now()->addSecond(10);
57 dispatch(new VerifyEmailJob($user))->delay($on);
58 return redirect()->route('landingPage')->with(['success'=>'We sent verifying email check it']);
59}
60 <?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->user= $user;
85 }
86
87 /**
88 * Execute the job.
89 *
90 * @return void
91 */
92 public function handle()
93 {
94 Mail::to($this->user->email)->send(new VerifyEmail($this->user));
95
96 }
97}
98 <?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->user = $user;
120 }
121 /**
122 * Build the message.
123 *
124 * @return $this
125 */
126 public function build()
127 {
128 $user = $this->user;
129 return $this->subject('Mail from Oneme')
130 ->view('site.auth.verifyEmail',compact('user'));
131 }
132}
133APP_URL = "https://example.com" #change this with your application url
134<img src={{ env('APP_URL') . '/static/logo.png' }} />
135
QUESTION
FirebaseOptions cannot be null when creating the default app
Asked 2021-Dec-25 at 09:13I 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"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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<!DOCTYPE html>
17<html>
18<head>
19 <!--
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 "/" 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 -->
32 <base href="$FLUTTER_BASE_HREF">
33
34 <meta charset="UTF-8">
35 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
36 <meta name="description" content="A new Flutter project.">
37 <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
38 <!-- iOS meta tags & icons -->
39 <meta name="apple-mobile-web-app-capable" content="yes">
40 <meta name="apple-mobile-web-app-status-bar-style" content="black">
41 <meta name="apple-mobile-web-app-title" content="signin_example">
42 <link rel="apple-touch-icon" href="icons/Icon-192.png">
43
44 <!-- Favicon -->
45 <link rel="icon" type="image/png" href="favicon.png"/>
46
47 <title>signin_example</title>
48 <link rel="manifest" href="manifest.json">
49</head>
50<body>
51 <!-- 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 -->
54
55
56 <script>
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 <script> 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) => {
79 function waitForActivation(serviceWorker) {
80 serviceWorker.addEventListener('statechange', () => {
81 if (serviceWorker.state == 'activated') {
82 console.log('Installed new service worker.');
83 loadMainDartJs();
84 }
85 });
86 }
87 if (!reg.active && (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 <script> tag.
106 setTimeout(() => {
107 if (!scriptLoaded) {
108 console.warn(
109 'Failed to load app from service worker. Falling back to plain <script> tag.',
110 );
111 loadMainDartJs();
112 }
113 }, 4000);
114 });
115 } else {
116 // Service workers not supported. Just drop the <script> tag.
117 loadMainDartJs();
118 }
119 </script>
120 <script type="module">
121 // Import the functions you need from the SDKs you need
122 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
123 import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
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: "xxx",
131 authDomain: "xxx",
132 projectId: "xx",
133 storageBucket: "exxx",
134 messagingSenderId: "xxx",
135 appId: "xxx",
136 measurementId: "xxx"
137 };
138
139 // Initialize Firebase
140 const app = initializeApp(firebaseConfig);
141 const analytics = getAnalytics(app);
142 </script>
143</body>
144</html>
145
Part of code from main.dart file where firebase initialisation is happening
1"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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<!DOCTYPE html>
17<html>
18<head>
19 <!--
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 "/" 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 -->
32 <base href="$FLUTTER_BASE_HREF">
33
34 <meta charset="UTF-8">
35 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
36 <meta name="description" content="A new Flutter project.">
37 <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
38 <!-- iOS meta tags & icons -->
39 <meta name="apple-mobile-web-app-capable" content="yes">
40 <meta name="apple-mobile-web-app-status-bar-style" content="black">
41 <meta name="apple-mobile-web-app-title" content="signin_example">
42 <link rel="apple-touch-icon" href="icons/Icon-192.png">
43
44 <!-- Favicon -->
45 <link rel="icon" type="image/png" href="favicon.png"/>
46
47 <title>signin_example</title>
48 <link rel="manifest" href="manifest.json">
49</head>
50<body>
51 <!-- 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 -->
54
55
56 <script>
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 <script> 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) => {
79 function waitForActivation(serviceWorker) {
80 serviceWorker.addEventListener('statechange', () => {
81 if (serviceWorker.state == 'activated') {
82 console.log('Installed new service worker.');
83 loadMainDartJs();
84 }
85 });
86 }
87 if (!reg.active && (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 <script> tag.
106 setTimeout(() => {
107 if (!scriptLoaded) {
108 console.warn(
109 'Failed to load app from service worker. Falling back to plain <script> tag.',
110 );
111 loadMainDartJs();
112 }
113 }, 4000);
114 });
115 } else {
116 // Service workers not supported. Just drop the <script> tag.
117 loadMainDartJs();
118 }
119 </script>
120 <script type="module">
121 // Import the functions you need from the SDKs you need
122 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
123 import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
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: "xxx",
131 authDomain: "xxx",
132 projectId: "xx",
133 storageBucket: "exxx",
134 messagingSenderId: "xxx",
135 appId: "xxx",
136 measurementId: "xxx"
137 };
138
139 // Initialize Firebase
140 const app = initializeApp(firebaseConfig);
141 const analytics = getAnalytics(app);
142 </script>
143</body>
144</html>
145void main() async {
146 WidgetsFlutterBinding.ensureInitialized();
147 await Firebase.initializeApp();
148 runApp(SignUpApp());
149}
150
Pubsec.yaml file of the project
1"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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<!DOCTYPE html>
17<html>
18<head>
19 <!--
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 "/" 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 -->
32 <base href="$FLUTTER_BASE_HREF">
33
34 <meta charset="UTF-8">
35 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
36 <meta name="description" content="A new Flutter project.">
37 <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
38 <!-- iOS meta tags & icons -->
39 <meta name="apple-mobile-web-app-capable" content="yes">
40 <meta name="apple-mobile-web-app-status-bar-style" content="black">
41 <meta name="apple-mobile-web-app-title" content="signin_example">
42 <link rel="apple-touch-icon" href="icons/Icon-192.png">
43
44 <!-- Favicon -->
45 <link rel="icon" type="image/png" href="favicon.png"/>
46
47 <title>signin_example</title>
48 <link rel="manifest" href="manifest.json">
49</head>
50<body>
51 <!-- 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 -->
54
55
56 <script>
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 <script> 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) => {
79 function waitForActivation(serviceWorker) {
80 serviceWorker.addEventListener('statechange', () => {
81 if (serviceWorker.state == 'activated') {
82 console.log('Installed new service worker.');
83 loadMainDartJs();
84 }
85 });
86 }
87 if (!reg.active && (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 <script> tag.
106 setTimeout(() => {
107 if (!scriptLoaded) {
108 console.warn(
109 'Failed to load app from service worker. Falling back to plain <script> tag.',
110 );
111 loadMainDartJs();
112 }
113 }, 4000);
114 });
115 } else {
116 // Service workers not supported. Just drop the <script> tag.
117 loadMainDartJs();
118 }
119 </script>
120 <script type="module">
121 // Import the functions you need from the SDKs you need
122 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
123 import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
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: "xxx",
131 authDomain: "xxx",
132 projectId: "xx",
133 storageBucket: "exxx",
134 messagingSenderId: "xxx",
135 appId: "xxx",
136 measurementId: "xxx"
137 };
138
139 // Initialize Firebase
140 const app = initializeApp(firebaseConfig);
141 const analytics = getAnalytics(app);
142 </script>
143</body>
144</html>
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: ">=2.15.0-268.18.beta <3.0.0"
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:13UPDATE:
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"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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<!DOCTYPE html>
17<html>
18<head>
19 <!--
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 "/" 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 -->
32 <base href="$FLUTTER_BASE_HREF">
33
34 <meta charset="UTF-8">
35 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
36 <meta name="description" content="A new Flutter project.">
37 <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
38 <!-- iOS meta tags & icons -->
39 <meta name="apple-mobile-web-app-capable" content="yes">
40 <meta name="apple-mobile-web-app-status-bar-style" content="black">
41 <meta name="apple-mobile-web-app-title" content="signin_example">
42 <link rel="apple-touch-icon" href="icons/Icon-192.png">
43
44 <!-- Favicon -->
45 <link rel="icon" type="image/png" href="favicon.png"/>
46
47 <title>signin_example</title>
48 <link rel="manifest" href="manifest.json">
49</head>
50<body>
51 <!-- 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 -->
54
55
56 <script>
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 <script> 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) => {
79 function waitForActivation(serviceWorker) {
80 serviceWorker.addEventListener('statechange', () => {
81 if (serviceWorker.state == 'activated') {
82 console.log('Installed new service worker.');
83 loadMainDartJs();
84 }
85 });
86 }
87 if (!reg.active && (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 <script> tag.
106 setTimeout(() => {
107 if (!scriptLoaded) {
108 console.warn(
109 'Failed to load app from service worker. Falling back to plain <script> tag.',
110 );
111 loadMainDartJs();
112 }
113 }, 4000);
114 });
115 } else {
116 // Service workers not supported. Just drop the <script> tag.
117 loadMainDartJs();
118 }
119 </script>
120 <script type="module">
121 // Import the functions you need from the SDKs you need
122 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
123 import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
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: "xxx",
131 authDomain: "xxx",
132 projectId: "xx",
133 storageBucket: "exxx",
134 messagingSenderId: "xxx",
135 appId: "xxx",
136 measurementId: "xxx"
137 };
138
139 // Initialize Firebase
140 const app = initializeApp(firebaseConfig);
141 const analytics = getAnalytics(app);
142 </script>
143</body>
144</html>
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: ">=2.15.0-268.18.beta <3.0.0"
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: "XXX",
195 appId: "XXX",
196 messagingSenderId: "XXX",
197 projectId: "XXX",
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:
- Install Flutterfire CLI:
1"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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<!DOCTYPE html>
17<html>
18<head>
19 <!--
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 "/" 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 -->
32 <base href="$FLUTTER_BASE_HREF">
33
34 <meta charset="UTF-8">
35 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
36 <meta name="description" content="A new Flutter project.">
37 <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
38 <!-- iOS meta tags & icons -->
39 <meta name="apple-mobile-web-app-capable" content="yes">
40 <meta name="apple-mobile-web-app-status-bar-style" content="black">
41 <meta name="apple-mobile-web-app-title" content="signin_example">
42 <link rel="apple-touch-icon" href="icons/Icon-192.png">
43
44 <!-- Favicon -->
45 <link rel="icon" type="image/png" href="favicon.png"/>
46
47 <title>signin_example</title>
48 <link rel="manifest" href="manifest.json">
49</head>
50<body>
51 <!-- 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 -->
54
55
56 <script>
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 <script> 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) => {
79 function waitForActivation(serviceWorker) {
80 serviceWorker.addEventListener('statechange', () => {
81 if (serviceWorker.state == 'activated') {
82 console.log('Installed new service worker.');
83 loadMainDartJs();
84 }
85 });
86 }
87 if (!reg.active && (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 <script> tag.
106 setTimeout(() => {
107 if (!scriptLoaded) {
108 console.warn(
109 'Failed to load app from service worker. Falling back to plain <script> tag.',
110 );
111 loadMainDartJs();
112 }
113 }, 4000);
114 });
115 } else {
116 // Service workers not supported. Just drop the <script> tag.
117 loadMainDartJs();
118 }
119 </script>
120 <script type="module">
121 // Import the functions you need from the SDKs you need
122 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
123 import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
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: "xxx",
131 authDomain: "xxx",
132 projectId: "xx",
133 storageBucket: "exxx",
134 messagingSenderId: "xxx",
135 appId: "xxx",
136 measurementId: "xxx"
137 };
138
139 // Initialize Firebase
140 const app = initializeApp(firebaseConfig);
141 const analytics = getAnalytics(app);
142 </script>
143</body>
144</html>
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: ">=2.15.0-268.18.beta <3.0.0"
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: "XXX",
195 appId: "XXX",
196 messagingSenderId: "XXX",
197 projectId: "XXX",
198 ),
199 );
200 runApp(MyApp());
201}
202dart pub global activate flutterfire_cli
203
- Configure Flutterfire (run in your project's root and go through the wizard selecting the correct Firebase project and target platforms):
1"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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<!DOCTYPE html>
17<html>
18<head>
19 <!--
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 "/" 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 -->
32 <base href="$FLUTTER_BASE_HREF">
33
34 <meta charset="UTF-8">
35 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
36 <meta name="description" content="A new Flutter project.">
37 <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
38 <!-- iOS meta tags & icons -->
39 <meta name="apple-mobile-web-app-capable" content="yes">
40 <meta name="apple-mobile-web-app-status-bar-style" content="black">
41 <meta name="apple-mobile-web-app-title" content="signin_example">
42 <link rel="apple-touch-icon" href="icons/Icon-192.png">
43
44 <!-- Favicon -->
45 <link rel="icon" type="image/png" href="favicon.png"/>
46
47 <title>signin_example</title>
48 <link rel="manifest" href="manifest.json">
49</head>
50<body>
51 <!-- 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 -->
54
55
56 <script>
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 <script> 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) => {
79 function waitForActivation(serviceWorker) {
80 serviceWorker.addEventListener('statechange', () => {
81 if (serviceWorker.state == 'activated') {
82 console.log('Installed new service worker.');
83 loadMainDartJs();
84 }
85 });
86 }
87 if (!reg.active && (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 <script> tag.
106 setTimeout(() => {
107 if (!scriptLoaded) {
108 console.warn(
109 'Failed to load app from service worker. Falling back to plain <script> tag.',
110 );
111 loadMainDartJs();
112 }
113 }, 4000);
114 });
115 } else {
116 // Service workers not supported. Just drop the <script> tag.
117 loadMainDartJs();
118 }
119 </script>
120 <script type="module">
121 // Import the functions you need from the SDKs you need
122 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
123 import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
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: "xxx",
131 authDomain: "xxx",
132 projectId: "xx",
133 storageBucket: "exxx",
134 messagingSenderId: "xxx",
135 appId: "xxx",
136 measurementId: "xxx"
137 };
138
139 // Initialize Firebase
140 const app = initializeApp(firebaseConfig);
141 const analytics = getAnalytics(app);
142 </script>
143</body>
144</html>
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: ">=2.15.0-268.18.beta <3.0.0"
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: "XXX",
195 appId: "XXX",
196 messagingSenderId: "XXX",
197 projectId: "XXX",
198 ),
199 );
200 runApp(MyApp());
201}
202dart pub global activate flutterfire_cli
203flutterfire configure
204
- Import the automatically generated
firebase_options.dart
file in yourmain.dart
file and initializeFirebase
as follows:
1"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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<!DOCTYPE html>
17<html>
18<head>
19 <!--
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 "/" 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 -->
32 <base href="$FLUTTER_BASE_HREF">
33
34 <meta charset="UTF-8">
35 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
36 <meta name="description" content="A new Flutter project.">
37 <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
38 <!-- iOS meta tags & icons -->
39 <meta name="apple-mobile-web-app-capable" content="yes">
40 <meta name="apple-mobile-web-app-status-bar-style" content="black">
41 <meta name="apple-mobile-web-app-title" content="signin_example">
42 <link rel="apple-touch-icon" href="icons/Icon-192.png">
43
44 <!-- Favicon -->
45 <link rel="icon" type="image/png" href="favicon.png"/>
46
47 <title>signin_example</title>
48 <link rel="manifest" href="manifest.json">
49</head>
50<body>
51 <!-- 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 -->
54
55
56 <script>
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 <script> 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) => {
79 function waitForActivation(serviceWorker) {
80 serviceWorker.addEventListener('statechange', () => {
81 if (serviceWorker.state == 'activated') {
82 console.log('Installed new service worker.');
83 loadMainDartJs();
84 }
85 });
86 }
87 if (!reg.active && (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 <script> tag.
106 setTimeout(() => {
107 if (!scriptLoaded) {
108 console.warn(
109 'Failed to load app from service worker. Falling back to plain <script> tag.',
110 );
111 loadMainDartJs();
112 }
113 }, 4000);
114 });
115 } else {
116 // Service workers not supported. Just drop the <script> tag.
117 loadMainDartJs();
118 }
119 </script>
120 <script type="module">
121 // Import the functions you need from the SDKs you need
122 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
123 import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
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: "xxx",
131 authDomain: "xxx",
132 projectId: "xx",
133 storageBucket: "exxx",
134 messagingSenderId: "xxx",
135 appId: "xxx",
136 measurementId: "xxx"
137 };
138
139 // Initialize Firebase
140 const app = initializeApp(firebaseConfig);
141 const analytics = getAnalytics(app);
142 </script>
143</body>
144</html>
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: ">=2.15.0-268.18.beta <3.0.0"
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: "XXX",
195 appId: "XXX",
196 messagingSenderId: "XXX",
197 projectId: "XXX",
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"FirebaseOptions cannot be null when creating the default app."
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 (<anonymous>)
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<!DOCTYPE html>
17<html>
18<head>
19 <!--
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 "/" 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 -->
32 <base href="$FLUTTER_BASE_HREF">
33
34 <meta charset="UTF-8">
35 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
36 <meta name="description" content="A new Flutter project.">
37 <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
38 <!-- iOS meta tags & icons -->
39 <meta name="apple-mobile-web-app-capable" content="yes">
40 <meta name="apple-mobile-web-app-status-bar-style" content="black">
41 <meta name="apple-mobile-web-app-title" content="signin_example">
42 <link rel="apple-touch-icon" href="icons/Icon-192.png">
43
44 <!-- Favicon -->
45 <link rel="icon" type="image/png" href="favicon.png"/>
46
47 <title>signin_example</title>
48 <link rel="manifest" href="manifest.json">
49</head>
50<body>
51 <!-- 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 -->
54
55
56 <script>
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 <script> 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) => {
79 function waitForActivation(serviceWorker) {
80 serviceWorker.addEventListener('statechange', () => {
81 if (serviceWorker.state == 'activated') {
82 console.log('Installed new service worker.');
83 loadMainDartJs();
84 }
85 });
86 }
87 if (!reg.active && (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 <script> tag.
106 setTimeout(() => {
107 if (!scriptLoaded) {
108 console.warn(
109 'Failed to load app from service worker. Falling back to plain <script> tag.',
110 );
111 loadMainDartJs();
112 }
113 }, 4000);
114 });
115 } else {
116 // Service workers not supported. Just drop the <script> tag.
117 loadMainDartJs();
118 }
119 </script>
120 <script type="module">
121 // Import the functions you need from the SDKs you need
122 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
123 import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
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: "xxx",
131 authDomain: "xxx",
132 projectId: "xx",
133 storageBucket: "exxx",
134 messagingSenderId: "xxx",
135 appId: "xxx",
136 measurementId: "xxx"
137 };
138
139 // Initialize Firebase
140 const app = initializeApp(firebaseConfig);
141 const analytics = getAnalytics(app);
142 </script>
143</body>
144</html>
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: ">=2.15.0-268.18.beta <3.0.0"
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: "XXX",
195 appId: "XXX",
196 messagingSenderId: "XXX",
197 projectId: "XXX",
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 <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
212 <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script>
213 <script>
214 var firebaseConfig = {
215 apiKey: "xxx",
216 authDomain: "xxx",
217 projectId: "xx",
218 storageBucket: "exxx",
219 messagingSenderId: "xxx",
220 appId: "xxx",
221 measurementId: "xxx"
222 };
223
224 firebase.initializeApp(firebaseConfig);
225 firebase.analytics();
226 </script>
227
QUESTION
Wrong og:image is appearing on page metadata
Asked 2021-Dec-22 at 02:16In my [id].tsx
page I have the following meta tag structure
1<Head>
2 <meta property="og:title" content={'íęł - ' + archive.title} key="title" />
3 <meta property="og:type" content="article" key="type" />
4 {imageUrl && <meta property="og:image" content={imageUrl} key="image" />}
5</Head>
6
However in my production server, when I scrape an article using the Facebook debugger I get the following error
But when I check for an article in my development server, the proper image shows even though the code is the same as production
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<Head>
2 <meta property="og:title" content={'íęł - ' + archive.title} key="title" />
3 <meta property="og:type" content="article" key="type" />
4 {imageUrl && <meta property="og:image" content={imageUrl} key="image" />}
5</Head>
6<link rel="canonical" href="https://poomgo.com/" />
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<Head>
2 <meta property="og:title" content={'íęł - ' + archive.title} key="title" />
3 <meta property="og:type" content="article" key="type" />
4 {imageUrl && <meta property="og:image" content={imageUrl} key="image" />}
5</Head>
6<link rel="canonical" href="https://poomgo.com/" />
7const { data: archive, error } = useSWR('/archives/' + router.query.id, (url) => {
8 return axios.get(url).then(res => 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<Head>
2 <meta property="og:title" content={'íęł - ' + archive.title} key="title" />
3 <meta property="og:type" content="article" key="type" />
4 {imageUrl && <meta property="og:image" content={imageUrl} key="image" />}
5</Head>
6<link rel="canonical" href="https://poomgo.com/" />
7const { data: archive, error } = useSWR('/archives/' + router.query.id, (url) => {
8 return axios.get(url).then(res => res.data)
9 }, {
10 initialData: props.data
11 })
12const images = archive.images
13 let imageUrl = ''
14
15 if (images && images.length > 0) {
16 imageUrl = getCloundFrontUrl(images[0].url)
17 }
18
I then use the getCloundFrontUrl
function to replace the url with my cdn
1<Head>
2 <meta property="og:title" content={'íęł - ' + archive.title} key="title" />
3 <meta property="og:type" content="article" key="type" />
4 {imageUrl && <meta property="og:image" content={imageUrl} key="image" />}
5</Head>
6<link rel="canonical" href="https://poomgo.com/" />
7const { data: archive, error } = useSWR('/archives/' + router.query.id, (url) => {
8 return axios.get(url).then(res => res.data)
9 }, {
10 initialData: props.data
11 })
12const images = archive.images
13 let imageUrl = ''
14
15 if (images && images.length > 0) {
16 imageUrl = getCloundFrontUrl(images[0].url)
17 }
18export const getCloundFrontUrl = (url) => {
19 return url ? url.replace('poomgo-homepage.s3.ap-northeast-2.amazonaws.com', 'cdn-hp.poomgo.com') : ''
20}
21
ANSWER
Answered 2021-Dec-22 at 02:16I removed the
1<Head>
2 <meta property="og:title" content={'íęł - ' + archive.title} key="title" />
3 <meta property="og:type" content="article" key="type" />
4 {imageUrl && <meta property="og:image" content={imageUrl} key="image" />}
5</Head>
6<link rel="canonical" href="https://poomgo.com/" />
7const { data: archive, error } = useSWR('/archives/' + router.query.id, (url) => {
8 return axios.get(url).then(res => res.data)
9 }, {
10 initialData: props.data
11 })
12const images = archive.images
13 let imageUrl = ''
14
15 if (images && images.length > 0) {
16 imageUrl = getCloundFrontUrl(images[0].url)
17 }
18export const getCloundFrontUrl = (url) => {
19 return url ? url.replace('poomgo-homepage.s3.ap-northeast-2.amazonaws.com', 'cdn-hp.poomgo.com') : ''
20}
21<link rel="canonical" href="https://poomgo.com/" />
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
QUESTION
React js change meta tags dynamically
Asked 2021-Dec-20 at 07:50I 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: "User meta tags",
3 description: "Basically make the application responsive when on user side",
4 meta: {
5 name: { keywords: "viewport" },
6 content: "width=device-width, initial-scale=1",
7 },
8};
9const metaAdmin = {
10 title: "Admin meta tags",
11 description: "Make the application default in desktop mode",
12 meta: {
13 name: { keywords: "viewport" },
14 content: "width=1024",
15 },
16};
17
ANSWER
Answered 2021-Dec-20 at 07:50I 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: "User meta tags",
3 description: "Basically make the application responsive when on user side",
4 meta: {
5 name: { keywords: "viewport" },
6 content: "width=device-width, initial-scale=1",
7 },
8};
9const metaAdmin = {
10 title: "Admin meta tags",
11 description: "Make the application default in desktop mode",
12 meta: {
13 name: { keywords: "viewport" },
14 content: "width=1024",
15 },
16};
17import {Helmet} from "react-helmet";
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: "User meta tags",
3 description: "Basically make the application responsive when on user side",
4 meta: {
5 name: { keywords: "viewport" },
6 content: "width=device-width, initial-scale=1",
7 },
8};
9const metaAdmin = {
10 title: "Admin meta tags",
11 description: "Make the application default in desktop mode",
12 meta: {
13 name: { keywords: "viewport" },
14 content: "width=1024",
15 },
16};
17import {Helmet} from "react-helmet";
18
19 <Helmet>
20 <title>{`${admin ? "Admin Title" : "Client Title"}`}</title>
21 <meta name="description" content={`${admin ? "Admin Content" : "Client Content"}`} />
22 </Helmet>
23
24
QUESTION
Why is blazor HeadOutlet rendering after the App
Asked 2021-Nov-01 at 19:31I'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 "/"
2@namespace Example.Pages
3@using Microsoft.AspNetCore.Components.Web
4@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
5
6@{
7 Layout = null;
8}
9
10<!DOCTYPE html>
11<html lang="en">
12<head>
13 <component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
14 <base href="~/" />
15
16 <link href="css/site.css" rel="stylesheet" />
17 <link rel="preconnect" href="https://fonts.gstatic.com">
18</head>
19<body>
20 <component type="typeof(App)" render-mode="ServerPrerendered" />
21
22 <div id="blazor-error-ui">
23 <environment include="Staging,Production">
24 An error has occurred. This application may no longer respond until reloaded.
25 </environment>
26 <environment include="Development">
27 An unhandled exception has occurred. See browser dev tools for details.
28 </environment>
29 <a href="/" class="reload">Reload</a>
30 <a href="#" class="dismiss">đ</a>
31 </div>
32
33 <script src="_framework/blazor.server.js"></script>
34 <script src="~/outsideHandleContainerJsInterop.js"></script>
35</body>
36</html>
37
1@page "/"
2@namespace Example.Pages
3@using Microsoft.AspNetCore.Components.Web
4@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
5
6@{
7 Layout = null;
8}
9
10<!DOCTYPE html>
11<html lang="en">
12<head>
13 <component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
14 <base href="~/" />
15
16 <link href="css/site.css" rel="stylesheet" />
17 <link rel="preconnect" href="https://fonts.gstatic.com">
18</head>
19<body>
20 <component type="typeof(App)" render-mode="ServerPrerendered" />
21
22 <div id="blazor-error-ui">
23 <environment include="Staging,Production">
24 An error has occurred. This application may no longer respond until reloaded.
25 </environment>
26 <environment include="Development">
27 An unhandled exception has occurred. See browser dev tools for details.
28 </environment>
29 <a href="/" class="reload">Reload</a>
30 <a href="#" class="dismiss">đ</a>
31 </div>
32
33 <script src="_framework/blazor.server.js"></script>
34 <script src="~/outsideHandleContainerJsInterop.js"></script>
35</body>
36</html>
37@page "/test"
38
39<HeadContent>
40 <meta name="description" content="Hello World">
41</HeadContent>
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 "/"
2@namespace Example.Pages
3@using Microsoft.AspNetCore.Components.Web
4@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
5
6@{
7 Layout = null;
8}
9
10<!DOCTYPE html>
11<html lang="en">
12<head>
13 <component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
14 <base href="~/" />
15
16 <link href="css/site.css" rel="stylesheet" />
17 <link rel="preconnect" href="https://fonts.gstatic.com">
18</head>
19<body>
20 <component type="typeof(App)" render-mode="ServerPrerendered" />
21
22 <div id="blazor-error-ui">
23 <environment include="Staging,Production">
24 An error has occurred. This application may no longer respond until reloaded.
25 </environment>
26 <environment include="Development">
27 An unhandled exception has occurred. See browser dev tools for details.
28 </environment>
29 <a href="/" class="reload">Reload</a>
30 <a href="#" class="dismiss">đ</a>
31 </div>
32
33 <script src="_framework/blazor.server.js"></script>
34 <script src="~/outsideHandleContainerJsInterop.js"></script>
35</body>
36</html>
37@page "/test"
38
39<HeadContent>
40 <meta name="description" content="Hello World">
41</HeadContent>
42<!--Blazor:{"sequence":0,"type":"server","prerenderId":"b0376004567c4aaf9c07defc4341e21e","descriptor":"<long string here>"}--><!--Blazor:{"prerenderId":"b0376004567c4aaf9c07defc4341e21e"}-->
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:31This 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
QUESTION
Can't link flutter web application to firebase project / infinite loading
Asked 2021-Oct-28 at 10:21I 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: ">=2.6.0 <3.0.0"
8
9dependencies:
10 flutter:
11 sdk: flutter
12 provider: ^4.0.4
13 firebase_core: "^1.7.0"
14 cloud_firestore: "^2.5.3"
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: ">=2.6.0 <3.0.0"
8
9dependencies:
10 flutter:
11 sdk: flutter
12 provider: ^4.0.4
13 firebase_core: "^1.7.0"
14 cloud_firestore: "^2.5.3"
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<!DOCTYPE html>
26<html lang="en">
27<head>
28 <!--
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 "/" 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 -->
41 <base href="$FLUTTER_BASE_HREF">
42
43 <meta charset="UTF-8">
44 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
45 <meta name="description" content="A new Flutter project.">
46
47 <!-- iOS meta tags & icons -->
48 <meta name="apple-mobile-web-app-capable" content="yes">
49 <meta name="apple-mobile-web-app-status-bar-style" content="black">
50 <meta name="apple-mobile-web-app-title" content="flutter_application_1">
51 <link rel="apple-touch-icon" href="icons/Icon-192.png">
52
53 <title>flutter_application_1</title>
54 <link rel="manifest" href="manifest.json">
55</head>
56<body>
57
58 <script>
59 import { initializeApp } from "firebase/app";
60 import { } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"
61 import { } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js"
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: "...",
68 authDomain: "...",
69 databaseURL: "...",
70 projectId: "...",
71 storageBucket: "...",
72 messagingSenderId: "...",
73 appId: "..."
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 <script> 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) => {
102 function waitForActivation(serviceWorker) {
103 serviceWorker.addEventListener('statechange', () => {
104 if (serviceWorker.state == 'activated') {
105 console.log('Installed new service worker.');
106 loadMainDartJs();
107 }
108 });
109 }
110 if (!reg.active && (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 <script> tag.
129 setTimeout(() => {
130 if (!scriptLoaded) {
131 console.warn(
132 'Failed to load app from service worker. Falling back to plain <script> tag.',
133 );
134 loadMainDartJs();
135 }
136 }, 4000);
137 });
138 } else {
139 // Service workers not supported. Just drop the <script> tag.
140 loadMainDartJs();
141 }
142 </script>
143</body>
144</html>
145
and my main.dart
:
1name: flutter_web_diary
2description: A new Flutter project.
3
4version: 1.0.0+1
5
6environment:
7 sdk: ">=2.6.0 <3.0.0"
8
9dependencies:
10 flutter:
11 sdk: flutter
12 provider: ^4.0.4
13 firebase_core: "^1.7.0"
14 cloud_firestore: "^2.5.3"
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<!DOCTYPE html>
26<html lang="en">
27<head>
28 <!--
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 "/" 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 -->
41 <base href="$FLUTTER_BASE_HREF">
42
43 <meta charset="UTF-8">
44 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
45 <meta name="description" content="A new Flutter project.">
46
47 <!-- iOS meta tags & icons -->
48 <meta name="apple-mobile-web-app-capable" content="yes">
49 <meta name="apple-mobile-web-app-status-bar-style" content="black">
50 <meta name="apple-mobile-web-app-title" content="flutter_application_1">
51 <link rel="apple-touch-icon" href="icons/Icon-192.png">
52
53 <title>flutter_application_1</title>
54 <link rel="manifest" href="manifest.json">
55</head>
56<body>
57
58 <script>
59 import { initializeApp } from "firebase/app";
60 import { } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"
61 import { } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js"
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: "...",
68 authDomain: "...",
69 databaseURL: "...",
70 projectId: "...",
71 storageBucket: "...",
72 messagingSenderId: "...",
73 appId: "..."
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 <script> 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) => {
102 function waitForActivation(serviceWorker) {
103 serviceWorker.addEventListener('statechange', () => {
104 if (serviceWorker.state == 'activated') {
105 console.log('Installed new service worker.');
106 loadMainDartJs();
107 }
108 });
109 }
110 if (!reg.active && (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 <script> tag.
129 setTimeout(() => {
130 if (!scriptLoaded) {
131 console.warn(
132 'Failed to load app from service worker. Falling back to plain <script> tag.',
133 );
134 loadMainDartJs();
135 }
136 }, 4000);
137 });
138 } else {
139 // Service workers not supported. Just drop the <script> tag.
140 loadMainDartJs();
141 }
142 </script>
143</body>
144</html>
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<void> 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() => _AppState();
172}
173
174class _AppState extends State<App> {
175 /// The future is part of the state of our widget. We should not call `initializeApp`
176 /// directly inside [build].
177 final Future<FirebaseApp> _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) => DiaryEntry.fromDoc(doc)).toList();
210 });
211 return StreamProvider<List<DiaryEntry>>(
212 create: (_) => 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) => MyHomePage(),
222 '/new-entry': (context) => 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() => _MyHomePageState();
236}
237
238class _MyHomePageState extends State<MyHomePage> {
239 @override
240 Widget build(BuildContext context) {
241 final diaryEntries = Provider.of<List<DiaryEntry>>(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: <Widget>[
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: () => 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:55For firebase in web there is a different package. Please check this one Firebase_core_web
QUESTION
Error when creating custom dashboard using WooCommerce REST API
Asked 2021-Oct-27 at 05:08I 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<?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' => true, // Enable the WP REST API integration
12 'version' => 'wc/v2' // WooCommerce WP REST API version
13
14 ]
15);
16
17//$products = $woocommerce->get('products');
18
19
20try {
21
22 $results = $woocommerce->get('orders');
23 $products = $woocommerce->get('products');
24 $customers = $woocommerce->get('customers');
25 $result = count($results);
26 $customer = count($customers);
27 $product = count($products);
28 $query = ['date_min' => '2017-10-01', 'date_max' => '2021-10-30'];
29 $sales = $woocommerce->get('reports/sales', $query);
30 $sale = $sales[0]->total_sales;
31
32 // Last request data.
33
34 $lastRequest = $woocommerce->http->getRequest();
35 $lastRequest->getUrl(); // Requested URL (string).
36 $lastRequest->getMethod(); // Request method (string).
37 $lastRequest->getParameters(); // Request parameters (array).
38 $lastRequest->getHeaders(); // Request headers (array).
39 $lastRequest->getBody(); // Request body (JSON).
40
41 // Last response data.
42
43 $lastResponse = $woocommerce->http->getResponse();
44 $lastResponse->getCode(); // Response code (int).
45 $lastResponse->getHeaders(); // Response headers (array).
46 $lastResponse->getBody(); // Response body (JSON).
47}
48
49catch(HttpClientException $e) {
50 $e->getMessage(); // Error message.
51 $e->getRequest(); // Last request data.
52 $e->getResponse(); // Last response data.
53}
54
55if (isset($_POST['btn-update'])) {
56 $status = $_POST['bookId'];
57 $st = $_POST['ostatus'];
58
59 $woocommerce->put('orders/' . $status, array(
60 'status' => $st
61 ));
62 header('Location: http://localhost:10053/');
63}
64
65
66if (isset($_POST['btn-delete'])) {
67 $oid = $_POST['cId'];
68
69 $woocommerce->delete('orders/' . $oid, ['force' => true]);
70 header('Location: http://localhost:10053/');
71}
72
73?>
74
75
76<!DOCTYPE html>
77<html lang="en">
78
79<head>
80 <meta charset="utf-8">
81 <meta http-equiv="X-UA-Compatible" content="IE=edge">
82 <meta name="viewport" content="width=device-width, initial-scale=1">
83 <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
84 <meta name="description" content="">
85 <meta name="author" content="">
86 <link rel="icon" href="../../favicon.ico">
87 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
88
89 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
90 <link rel="stylesheet" href="style.css" />
91
92 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
93
94 <title>Dashboard Template for Bootstrap</title>
95
96</head>
97 <div class="container">
98 <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-1">
99 <h1 class="page-header">Dashboard</h1>
100
101 <div class="row placeholders">
102 <div class="col-xs-6 col-sm-3 placeholder">
103 <p id="large">
104 <?php echo $result?>
105 </p>
106 <hr>
107 <span class="text-muted">New Orders</span>
108 </div>
109 <div class="col-xs-6 col-sm-3 placeholder">
110 <p id="large">
111 <?php echo $customer?>
112 </p>
113 <hr>
114
115 <span class="text-muted">Customers</span>
116 </div>
117 <div class="col-xs-6 col-sm-3 placeholder">
118 <p id="large">
119 <?php echo $product?>
120 </p>
121 <hr>
122 <span class="text-muted">All Products</span>
123 </div>
124 <div class="col-xs-6 col-sm-3 placeholder">
125 <p id="large">
126 <?php echo $sale?>
127 </p>
128 <hr>
129 <span class="text-muted">Total Sales</span>
130 </div>
131 </div>
132 </div>
133 </div>
134 <div class="container">
135 <h2 class="sub-header">Orders List</h2>
136 <div class='table-responsive'>
137 <table id='myTable' class='table table-striped table-bordered'>
138 <thead>
139 <tr>
140 <th>Order #</th>
141 <th>Customer</th>
142 <th>Address</th>
143 <th>Contact</th>
144 <th>Order Date</th>
145 <th>Status</th>
146 <th>Actions</th>
147 </tr>
148 </thead>
149 <tbody>
150 <?php foreach ($results as $details){
151
152 echo "<tr><td>" . $details["id"]."</td>
153 <td>" . $details["billing"]["first_name"].$details["billing"]["last_name"]."</td>
154 <td>" . $details["shipping"]["address_1"]."</td>
155 <td>" . $details["billing"]["phone"]."</td>
156 <td>" . $details["date_created"]."</td>
157 <td>" . $details["status"]."</td>
158 <td><a class='open-AddBookDialog btn btn-primary' data-target='#myModal' data-id=".$details['id']." data-toggle='modal'>Update</a>
159 <a class='open-deleteDialog btn btn-danger' data-target='#myModal1' data-id=".$details['id']." data-toggle='modal'>Delete</a></td></tr>";
160 }
161 ?>
162 </tbody>
163 </table>
164 </div>
165 </div>
166
167 <div class="container">
168 <h2 class="sub-header">Customers List</h2>
169 <div class='table-responsive'>
170 <table id='myTable' class='table table-striped table-bordered'>
171 <thead>
172 <tr>
173 <th>Email</th>
174 <th>Name</th>
175 <th>Billing Address</th>
176 <th>Total Orders</th>
177 <th>Total spent</th>
178 <th>Avatar</th>
179 </tr>
180 </thead>
181 <tbody>
182 <?php
183 foreach($customers as $customer){
184
185 echo "<tr><td>" . $customer["email"]."</td>
186 <td>" . $customer["first_name"].$customer["last_name"]."</td>
187 <td>" . $customer["billing"]["address_1"]."</td>
188 <td>" . $customer["orders_count"]."</td>
189 <td>" . $customer["total_spent"]."</td>
190 <td><img height='50px' width='50px' src='".$customer["avatar_url"]."'></td></tr>";
191 }
192
193 ?>
194 </tbody>
195 </table>
196 </div>
197 </div>
198
199 <div class="container">
200 <h2 class="sub-header">Products List</h2>
201 <div class='table-responsive'>
202 <table id='myTable' class='table table-striped table-bordered'>
203 <thead>
204 <tr>
205 <th>SKU</th>
206 <th>Name</th>
207 <th>Status</th>
208 <th>Price</th>
209 <th>Total Sales</th>
210 <th>Picture</th>
211 </tr>
212 </thead>
213 <tbody>
214 <?php
215 foreach($products as $product){
216
217 echo "<tr><td>" . $product["sku"]."</td>
218 <td>" . $product["name"]."</td>
219 <td>" . $product["status"]."</td>
220 <td>" . $product["price"]."</td>
221 <td>" . $product["total_sales"]."</td>
222 <td><img height='50px' width='50px' src='".$product["images"][0]["src"]."'></td></tr>";
223 }
224
225 ?>
226 </tbody>
227 </table>
228 </div>
229 </div>
230
231 <div class="modal fade" id="myModal" role="dialog">
232 <div class="modal-dialog">
233
234 <!-- Modal content-->
235 <div class="modal-content">
236 <div class="modal-header">
237 <button type="button" class="close" data-dismiss="modal">&times;</button>
238 <h4 class="modal-title">Update Order Status</h4>
239 </div>
240 <div class="modal-body">
241 <p>Order ID:</p>
242 <form action="" method="post">
243 <div class="form-group">
244 <input type="text" class="form-control" name="bookId" id="bookId" value="">
245
246 <p for="sel1">Select list (select one):</p>
247 <select class="form-control" id="status" name="ostatus">
248 <option>Pending Payment</option>
249 <option>processing</option>
250 <option>On Hold</option>
251 <option>completed</option>
252 <option>Cancelled</option>
253 <option>Refunded</option>
254 <option>Failed</option>
255 </select>
256
257 </div>
258
259 <div class="modal-footer">
260 <button type="submit" class="btn btn-block" name="btn-update">Update</button>
261 </div>
262 </form>
263 </div>
264 </div>
265 </div>
266</div>
267
268<div class="modal fade" id="myModal1" role="dialog">
269 <div class="modal-dialog">
270
271 <!-- Modal content-->
272 <div class="modal-content">
273 <div class="modal-header">
274 <button type="button" class="close" data-dismiss="modal">&times;</button>
275 <h4 class="modal-title">Confirm Order Deletion</h4>
276 </div>
277 <div class="modal-body">
278 <p>Really you want to delete order?</p>
279 <form action="" method="post">
280 <div class="form-group">
281 <input type="text" class="form-control" name="cId" id="cId" value="">
282 </div>
283
284 <div class="modal-footer">
285 <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
286 <button type="submit" class="btn btn-danger" name="btn-delete">Delete</button>
287 </div>
288 </form>
289 </div>
290 </div>
291 </div>
292</div>
293
294
295
296 <script>
297 $(document).on("click", ".open-AddBookDialog", function() {
298 var myBookId = $(this).data('id');
299 $(".modal-body #bookId").val(myBookId);
300 });
301 </script>
302
303
304 <script>
305 $(document).on("click", ".open-deleteDialog", function() {
306 var myBook = $(this).data('id');
307 $(".modal-body #cId").val(myBook);
308 });
309 </script>
310
311
312</body>
313
314</html>
315
ANSWER
Answered 2021-Oct-22 at 07:53Try $details->id instead of $details["id"], and so on
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