getServerSession() returning null in api route when using NextJs and Next-Auth - next.js

I'm new to NextJS and Next-Auth.
I'm trying to write a secure api route that is only available if a user is logged in.
I sucessfully accessing the session on the client side using useSession() but when I try to implement the logic in an api route the session always returns null.
I have tried to copy the simpliest example from the docs. Am I missing something?
Here is my route in src/pages/api/users/getUser.ts:
import { getServerSession } from 'next-auth/next'
import { authOptions } from '../auth/[...nextauth]'
import { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions)
console.log('session', session)
if (session) {
res.send({ content: 'SUCCESS' })
} else {
res.send({ error: 'ERROR' })
}
}
Here is my authOptions in src/pages/api/auth/[...nextauth].ts
import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
import { PrismaAdapter } from '#next-auth/prisma-adapter'
import prisma from '../../../../prisma/db/prismadb'
export const authOptions = {
adapter: PrismaAdapter(prisma),
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID || '',
clientSecret: process.env.GITHUB_SECRET || '',
}),
],
pages: {
signIn: '/',
signOut: '/',
},
}
export default NextAuth(authOptions)
Here are my dependencies:
"dependencies": {
"#next-auth/prisma-adapter": "^1.0.5",
"#next/font": "13.1.6",
"#prisma/client": "^4.10.1",
"#types/node": "18.11.19",
"#types/react": "18.0.27",
"#types/react-dom": "18.0.10",
"axios": "^1.3.2",
"dotenv-cli": "^7.0.0",
"eslint": "8.33.0",
"eslint-config-next": "13.1.6",
"next": "13.1.6",
"next-auth": "^4.19.2",
"prisma": "^4.9.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"styled-components": "^5.3.6",
"typescript": "4.9.5"
},
"devDependencies": {
"#types/styled-components": "^5.1.26"
}

In my case, when NEXTAUTH_URL is 127.0.0.1 and API is requested to localhost, the session is null.
So, I solved the problem by matching the NEXTAUTH_URL with the request URL.

Related

Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/vue-router.js' does not provide an export named 'default'

I'm having some issues with installing vue-router with laravel. Laravel 9, Vue.js 3
routes.js
import AllBooks from './components/AllBooks.vue';
import CreateBook from './components/CreateBook.vue';
import EditBook from './components/EditBook.vue';
export const routes = [
{
name: 'home',
path: '/',
component: AllBooks
},
{
name: 'create',
path: '/create',
component: CreateBook
},
{
name: 'edit',
path: '/edit/:id',
component: EditBook
}
];
Here's my config:-
resources/js/app.js
import './bootstrap';
import { createApp } from 'vue';
const app = createApp({})
import App from './App.vue';
import VueAxios from 'vue-axios';
import VueRouter from 'vue-router'; // problem!!
import axios from 'axios';
import { routes } from './routes';
const router = VueRouter.createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: VueRouter.createWebHashHistory(),
routes,
})
// Make sure to _use_ the router instance to make the
// whole app router-aware.
app.use(router)
app.mount('#app')
package.json
"devDependencies": {
"#popperjs/core": "^2.11.6",
"#vitejs/plugin-vue": "^3.0.1",
"axios": "^1.1.2",
"bootstrap": "^5.2.3",
"laravel-vite-plugin": "^0.7.2",
"lodash": "^4.17.19",
"postcss": "^8.1.14",
"sass": "^1.56.1",
"vite": "^4.0.0",
"vue": "^3.2.37"
},
"dependencies": {
"vue-axios": "^3.5.2",
"vue-router": "^4.1.6"
}
If you could help me with vue-router doesn't provide an export?
import VueRouter from '/node_modules/.vite/deps/vue-router.js?v=05a616f1';
In my case, look out for duplicated entries for our vue libraries. I had:-
resources/views/layouts/app.blade.php
<script src="https://unpkg.com/vue#3"></script>
<script src="https://unpkg.com/vue-router#4"></script>
AND
package.json
"dependencies": {
"vue": "^3.2.45",
"vue-router": "^4.1.6"
}
also, my config changed in:-
resources/js/app.js
import './bootstrap';
import * as Vue from 'vue';
import * as VueRouter from 'vue-router'; // alternative ways of importing
import LoginComponent from "./components/LoginComponent.vue";
import TestComponent from "./components/TestComponent.vue";
const Home = { template: '<div>Home</div>' }
const routes = [
{ path: '/', component: Home },
{ path: '/login', name: "Login", component: LoginComponent },
{ path: '/test', name: "Test", component: TestComponent },
]
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes,
})
const app = Vue.createApp({})
app.use(router)
app.mount('#app')
If this helps you, well keep truckin. :)

NullInjectorError: No provider for InjectionToken angularfire2.app.options! 2021

Okay I just started using angular firebase and I've been scratching my head for two days. Most of the tutorials out there are mostly for older versions of firebase
this is the error that I am receiving when I inject my authentication service to the component
Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[LoginService -> AngularFireAuth -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options]:
NullInjectorError: No provider for InjectionToken angularfire2.app.options!
NullInjectorError: R3InjectorError(AppModule)[LoginService -> AngularFireAuth -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options]:
NullInjectorError: No provider for InjectionToken angularfire2.app.options!
the following links haven't been helpful so far
Link1 Link2 Link3
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { LoginService } from 'src/services/login.service';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';
import { NotFoundComponent } from './components/not-found/not-found.component';
import { environment } from '../environments/environment';
import { initializeApp,provideFirebaseApp } from '#angular/fire/app';
import { provideAuth,getAuth } from '#angular/fire/auth';
import { provideDatabase,getDatabase } from '#angular/fire/database';
import { provideFirestore,getFirestore } from '#angular/fire/firestore';
import { AngularFirestore } from '#angular/fire/compat/firestore';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
NotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAuth(() => getAuth()),
provideDatabase(() => getDatabase()),
provideFirestore(() => getFirestore()),
FormsModule,
ReactiveFormsModule
],
providers: [LoginService],
bootstrap: [AppComponent]
})
export class AppModule { }
login.service.ts
import { Injectable } from '#angular/core';
import { AngularFireAuth } from '#angular/fire/compat/auth';
import { Router } from '#angular/router';
import { AngularFirestore } from '#angular/fire/compat/firestore';
#Injectable({
providedIn: 'root'
})
export class LoginService {
userLoggedIn: boolean;
constructor(private afAuth: AngularFireAuth, private router : Router, private afs: AngularFirestore) {
this.userLoggedIn = false;
}
loginUser(email: string, password: string): Promise<any> {
return this.afAuth.signInWithEmailAndPassword(email,password)
.then(() => {
console.log('Auth Service: loginUser: success');
this.router.navigate(['']);
})
.catch(error => {
console.log('Auth Service: login error...');
console.log('error code', error.code);
console.log('error', error);
if (error.code)
return { isValid: false, message: error.message };
else
return { isValid: false, message : "Login Error"}
});
}
}
login.component.ts
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { LoginService } from 'src/services/login.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginFormCtrl: FormGroup;
constructor(private LoginService: LoginService, private router: Router) {
this.loginFormCtrl = new FormGroup({
email: new FormControl('', Validators.required),
password: new FormControl(null, Validators.required)
})
}
ngOnInit(): void {
}
onLogin() {
if (this.loginFormCtrl.invalid)
return;
this.LoginService.loginUser(this.loginFormCtrl.value.email, this.loginFormCtrl.value.password).then((result) => {
if (result == null) {
console.log('logging in...');
this.router.navigate(['']);
}
else if (result.isValid == false) {
console.log('login error', result);
}
});
}
}
package.json
{
"name": "fire-base",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"#angular/animations": "~12.2.0",
"#angular/common": "~12.2.0",
"#angular/compiler": "~12.2.0",
"#angular/core": "~12.2.0",
"#angular/fire": "^7.1.1",
"#angular/forms": "~12.2.0",
"#angular/platform-browser": "~12.2.0",
"#angular/platform-browser-dynamic": "~12.2.0",
"#angular/router": "~12.2.0",
"rxjs": "~6.6.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4",
"firebase": "^9.1.0",
"rxfire": "^6.0.0"
},
"devDependencies": {
"#angular-devkit/build-angular": "~12.2.7",
"#angular/cli": "~12.2.7",
"#angular/compiler-cli": "~12.2.0",
"#types/jasmine": "~3.8.0",
"#types/node": "^12.11.1",
"jasmine-core": "~3.8.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.3.5"
}
}
The fix is actually really simple...
in your app.module.ts
import
import { FIREBASE_OPTIONS } from '#angular/fire/compat';
and then add this to the providers
providers: [
{ provide: FIREBASE_OPTIONS, useValue: environment.firebase }
],
It seems that AngularFire is in the middle of major changes that embrace Firebase's new modular API, but the documentation hasn't quite caught up. The gist is that the you are initializing the Firebase App using the new API, but trying to use Firebase resources with the old API.
The key is to look at the import statement. Compare old and new style of initializing the app:
import {AngularFireModule} from '#angular/fire/compat';
[...]
imports: [
AngularFireModule.initializeApp(environment.firebase),
]
vs.
import {initializeApp, provideFirebaseApp} from '#angular/fire/app';
[...]
imports: [
provideFirebaseApp( () => initializeApp(environment.firebase)),
]
Notice how the old style initialization is under the "compat" namespace. If you initialize your app this way, you must also use the compat libraries to access resources. For example, from the AngularFire docs:
import {AngularFirestore, AngularFirestoreDocument} from '#angular/fire/compat/firestore';
[...]
constructor(private afs: AngularFirestore) {
this.itemDoc = afs.doc<Item>('items/1');
this.item = this.itemDoc.valueChanges();
}
However, this doesn't work with the new style app initialization. Instead you must use something like this, adapted from the Firebase docs:
import {doc, Firestore, getDoc} from '#angular/fire/firestore';
[...]
constructor(private firestore: Firestore) { }
[...]
const docRef = doc(this.firestore, "cities", "SF");
const docSnap = await getDoc(docRef);
Why does it matter? I assume, but do not know, that the instance of the app is not shared between old and new.
So, the moral of the story:
Most of the documentation on the internet uses the old API. If you want to use that API, use the "compat" version of the library.
If you want to use the modern modular API, make sure you're not using the "compat" library. And the best bet is to refer to the Firebase documentation until the AngularFire team has had a chance to catch up.
I had the same problem today and I agree: there's many versions and their documentation is disappointing.
The solution (in my case)
For my setup (angular 11 + angular/fire 6.1.5) i had to put the following in my app.module.ts file:
...
imports: [
...
AngularFireModule.initializeApp(environment.firebase),
],
...
(For me environment.firebase contains my firebase config.)
Further analysis of the problem below, you can stop reading if you don't care
The documentation for angular/fire 7 will tell you to do this:
provideFirebaseApp(() => initializeApp(environment.firebase)),
Which I'm sure works great for version 7, but angular 11 automatically installs version 6, because that's compatible.
My issue was fixed when I used both versions of initialization
AngularFireModule.initializeApp(environment.firebase),
provideFirebaseApp(() => initializeApp(environment.firebase)),
I have the same issue using auth-guard.
Fixed it by dropping the compat in the import path.
Before
import { hasCustomClaim, canActivate } from '#angular/fire/compat/auth-guard';
After
import { hasCustomClaim, canActivate } from '#angular/fire/auth-guard';
On the file App.component.ts add the following provider object:
import { FIREBASE_OPTIONS } from '#angular/fire/compat';
#NgModule({
providers: [
{ provide: FIREBASE_OPTIONS, useValue: environment.firebaseConfig }
],
})
taked from: [https://www.angularfix.com/2022/03/angular-fire-no-provider-for.html][1]
As advised by #Daniel Eisenhardt I downgraded my angular version. And it is now working ! Angular : ~11.2.4
and running ng add #angular/fire installed a compatible version of angular fire. ("^6.1.5")
This is my updated file
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './component/home/home.component';
import { LoginComponent } from './component/login/login.component';
import { NotFoundComponent } from './component/not-found/not-found.component';
import { AngularFireModule } from '#angular/fire';
import { AngularFirestoreModule } from '#angular/fire/firestore';
import { AngularFireDatabaseModule } from '#angular/fire/database';
// import { AngularFireStorageModule } from '#angular/fire/storage';
import { environment } from '../environments/environment';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
NotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase)
AngularFirestoreModule,                              
AngularFireDatabaseModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
package.json
{
"name": "evnt-mgmnt-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"#angular/animations": "~11.2.14",
"#angular/common": "~11.2.14",
"#angular/compiler": "~11.2.14",
"#angular/core": "~11.2.14",
"#angular/fire": "^6.1.5",
"#angular/forms": "~11.2.14",
"#angular/platform-browser": "~11.2.14",
"#angular/platform-browser-dynamic": "~11.2.14",
"#angular/router": "~11.2.14",
"rxjs": "~6.6.0",
"tslib": "^2.0.0",
"zone.js": "~0.11.3",
"firebase": "^7.0 || ^8.0"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.1102.13",
"#angular/cli": "~11.2.15",
"#angular/compiler-cli": "~11.2.14",
"#types/jasmine": "~3.6.0",
"#types/node": "^12.11.1",
"codelyzer": "^6.0.0",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~6.1.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.5.0",
"protractor": "~7.0.0",
"ts-node": "~8.3.0",
"tslint": "~6.1.0",
"typescript": "~4.1.5",
"#angular-devkit/architect": ">= 0.900 < 0.1300",
"firebase-tools": "^8.0.0 || ^9.0.0",
"fuzzy": "^0.1.3",
"inquirer": "^6.2.2",
"inquirer-autocomplete-prompt": "^1.0.1",
"open": "^7.0.3",
"jsonc-parser": "^3.0.0"
}
}
This error is likely a sign that you've not fully migrated to v9 Firebase.
v9 Firebase
Examples of v9 Firebase code
https://dev.to/jdgamble555/angular-12-with-firebase-9-49a0
compat imports as an intermediate step
A simple first-step migration will require changing imports to compat versions.
This keeps code working but you'll not benefit from v9 tree-shaking.
The compat imports gives APIs compatible with v8 code BUT the provide methods e.g. provideFirebaseApp won't work until all imports are v9 imports i.e. back to not being compat imports.
So until ALL your relevant code is upgraded to v9 use the old way
import { AngularFireAuthModule } from '#angular/fire/compat/auth';
import { AngularFireModule } from '#angular/fire/compat';
import { AngularFirestoreModule } from '#angular/fire/compat/firestore';
import { AngularFireAuthGuardModule } from '#angular/fire/compat/auth-guard';
#NgModule({
declarations: [
...
],
imports: [
...
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
AngularFireAuthModule,
AngularFireAuthGuardModule,
],
...
})
export class AppModule { }
Once your code is fully migrated go back to the provide methods:
import { initializeApp, provideFirebaseApp } from '#angular/fire/app';
import { provideAuth, getAuth } from '#angular/fire/auth';
import { provideFirestore, getFirestore } from '#angular/fire/firestore';
#NgModule({
declarations: [
...
],
imports: [
...
// firebase
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAuth(() => getAuth()),
provideFirestore(() => getFirestore()),

Vuetify CSS missing when i build for production

We purchased a web app written in Vue from someone and we developing to change/improve it. One thing we added was Vuetify so we can use the Vuetify elements and everything has been working great while in development mode, but when we build for production the CSS for Vuetify elements is missing.
I have searched for this online already and have already tried what everybody is suggesting without any luck.
Anybody has an idea of what could be wrong and why npm run build would be missing some of the CSS?
What's weird is that all the UI functionality for Vue elements is working perfectly, just the CSS is missing.
Please see code samples below.
main.js:
import '#fortawesome/fontawesome-free/css/all.css'
import Vue from "vue";
import App from "./App.vue";
import VueMoment from "vue-moment";
import VueAnalytics from "vue-analytics";
import VueMeta from "vue-meta";
import { library } from "#fortawesome/fontawesome-svg-core";
import {
faCoffee,
faPlusCircle,
faChartLine,
faChevronDown,
faMobile,
faEnvelope,
faClock,
faUsers,
faPaperPlane,
faCheckCircle,
faCheck,
faLeaf,
} from "#fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "#fortawesome/vue-fontawesome";
import axios from "axios";
import router from "./router";
import store from "./store";
import vuetify from './plugins/vuetify';
import Vuetify from 'vuetify/lib'
library.add([
faCoffee,
faPlusCircle,
faChartLine,
faChevronDown,
faMobile,
faEnvelope,
faClock,
faUsers,
faPaperPlane,
faCheckCircle,
faCheck,
faLeaf,
]);
Vue.use(VueAnalytics, {
id: "xxx",
router,
});
Vue.use(VueMoment);
Vue.use(VueMeta);
Vue.component("font-awesome-icon", FontAwesomeIcon);
Vue.use(Vuetify)
axios.interceptors.response.use(undefined, async function (error) {
if (error.response.status === 401) {
await store.dispatch("auth/logout");
router.push("/login");
}
return Promise.reject(error);
});
// Plugins
// ...
// Sass file
require("./assets/styles/main.css");
Vue.config.productionTip = false;
new Vue({
router,
store,
vuetify,
render: (h) => h(App)
}).$mount("#app");
App.vue:
<template>
<v-app>
<v-main>
<router-view/>
</v-main>
</v-app>
</template>
<style>
.text-white {
color: #fff !important;
}
.text-gray-600 {
color: #757575 !important;
}
.font-semibold, .text-gray-700 {
color: #616161 !important;
}
</style>
package.json:
{
"name": "reviewgrower-spa",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"deploy": "git push dokku master"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.25",
"#fortawesome/free-solid-svg-icons": "^5.11.2",
"#fortawesome/vue-fontawesome": "^0.1.8",
"#fullhuman/postcss-purgecss": "^1.3.0",
"axios": "^0.19.0",
"chart.js": "^2.9.4",
"core-js": "^2.6.10",
"i": "^0.3.6",
"jquery": "^3.5.1",
"npm": "^6.13.0",
"tailwindcss-spinner": "^0.2.0",
"tailwindcss-toggle": "github:TowelSoftware/tailwindcss-toggle",
"url-parse": "^1.4.7",
"vue": "^2.6.10",
"vue-analytics": "^5.17.2",
"vue-chartjs": "^3.5.1",
"vue-click-outside": "^1.0.7",
"vue-clickaway": "^2.2.2",
"vue-feather-icons": "^4.22.0",
"vue-js-toggle-button": "^1.3.3",
"vue-meta": "^1.6.0",
"vue-moment": "^4.0.0",
"vue-router": "^3.1.3",
"vue-stripe-elements-plus": "^0.2.10",
"vuetify": "^2.4.0",
"vuex": "^3.0.1",
"vuex-persist": "^2.1.1"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.15.2",
"#vue/cli-plugin-babel": "^3.12.1",
"#vue/cli-plugin-eslint": "^3.12.1",
"#vue/cli-service": "^3.12.1",
"babel-eslint": "^10.0.3",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.2.3",
"sass": "^1.32.0",
"sass-loader": "^7.1.0",
"tailwindcss": "^1.1.3",
"vue-cli-plugin-vuetify": "~2.1.0",
"vue-template-compiler": "^2.5.21",
"vuetify-loader": "^1.7.0"
}
}
It's a little tough to understand what is missing where. If you think that is just missing then please try adding css onto the HTML file from the cdn and check the working.
<link href="https://cdn.jsdelivr.net/npm/vuetify#2.x/dist/vuetify.min.css" rel="stylesheet">
I see that you are using webpack to compile the code. So, this could be also something related to webpack configuration. In your webpack rules do you have rules for css and scss. Because vuetify files are in scss.
My webpack configuration is as below when I do these type of circus.
--webpack.config.js--
const path = require("path");
const VuetifyLoaderPlugin = require("vuetify-loader/lib/plugin");
const { VueLoaderPlugin } = require("vue-loader");
module.exports = {
watch: true,
entry: {
main: 'main.js'
},
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.vue$/,
use: "vue-loader",
},
{
test: /\.s(c|a)ss$/,
use: [
"vue-style-loader",
"css-loader",
{
loader: "sass-loader",
// Requires sass-loader#^8.0.0
// options: {
// implementation: require('sass'),
// sassOptions: {
// fiber: require('fibers'),
// indentedSyntax: true // optional
// },
// },
},
],
},
],
},
plugins: [
new VueLoaderPlugin(),
new VuetifyLoaderPlugin({
/**
* This function will be called for every tag used in each vue component
* It should return an array, the first element will be inserted into the
* components array, the second should be a corresponding import
*
* originalTag - the tag as it was originally used in the template
* kebabTag - the tag normalised to kebab-case
* camelTag - the tag normalised to PascalCase
* path - a relative path to the current .vue file
* component - a parsed representation of the current component
*/
match(originalTag, { kebabTag, camelTag, path, component }) {
if (kebabTag.startsWith("core-")) {
return [
camelTag,
`import ${camelTag} from '#/components/core/${camelTag.substring(
4
)}.vue'`,
];
}
},
}),
],
}
Check your postcss.config.js, see if it has something to do with the purgecss.
You have to config the whitelist to ignore the vuetify styles.
Here is a sample for your reference:
const autoprefixer = require("autoprefixer");
const postcssImport = require("postcss-import");
const purgecss = require("#fullhuman/postcss-purgecss");
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);
let plugins = [];
if (IS_PROD) {
plugins.push(postcssImport);
plugins.push(
purgecss({
content: [
"./src/**/*.vue",
"./public/**/*.html",
`./node_modules/vuetify/src/**/*.ts`,
`./node_modules/vuetify/dist/vuetify.css`
],
defaultExtractor (content) {
const contentWithoutStyleBlocks = content.replace(/<style[^]+?<\/style>/gi, '')
return contentWithoutStyleBlocks.match(/[A-Za-z0-9-_/:]*[A-Za-z0-9-_/]+/g) || []
},
safelist: [ /-(leave|enter|appear)(|-(to|from|active))$/, /^(?!(|.*?:)cursor-move).+-move$/, /^router-link(|-exact)-active$/, /data-v-.*/ ],
whitelist: [
'container',
'row',
'spacer',
'aos-animate',
'col',
'[type=button]',
'v-application p',
],
whitelistPatterns: [
/^v-.*/,
/^col-.*/,
/^theme-.*/,
/^rounded-.*/,
/^data-aos-.*/,
/^(red|grey)--text$/,
/^text--darken-[1-4]$/,
/^text--lighten-[1-4]$/
],
whitelistPatternsChildren: [
/^post-content/,
/^v-input/,
/^swiper-.*/,
/^pswp.*/,
/^v-text-field.*/,
/^v-progress-linear/
]
})
);
}
module.exports = {
plugins:[
require('cssnano')({
preset: 'default'
}),
require('postcss-pxtorem')({
remUnit:15, //每个rem对应的px值
threeVersion:true
}),
...plugins,autoprefixer
]
}``
You are simply missing an include in your main.js (see vuetify docs):
import 'vuetify/dist/vuetify.min.css'
This will ensure that webpack includes the vuetify styles in the bundled CSS for production. This fixed the same issue for me (i.e. it worked locally but not in production).

simpl-schema not working with autoform using meteor flow-db-admin

Currently using meteor flow-db-admin as admin template https://github.com/sachinbhutani/flow-db-admin
But the autoform doesn't seem to work with the simpl-schema as the labels don't show and the validation doesn't work
package.json
{
"name": "tours",
"private": true,
"scripts": {
"start": "meteor run",
"test": "meteor test --once --driver-package meteortesting:mocha",
"test-app": "TEST_WATCH=1 meteor test --full-app --driver-package meteortesting:mocha",
"visualize": "meteor --production --extra-packages bundle-visualizer"
},
"dependencies": {
"#babel/runtime": "^7.1.5",
"bcrypt": "^3.0.0",
"classnames": "^2.2.6",
"meteor-node-stubs": "^0.4.1",
"react": "^16.4.2",
"react-addons-pure-render-mixin": "^15.6.2",
"react-dom": "^16.4.2",
"react-mounter": "^1.2.0",
"simpl-schema": "^1.5.3"
},
"meteor": {
"mainModule": {
"client": "client/main.js",
"server": "server/main.js"
},
"testModule": "tests/main.js"
},
"devDependencies": {
"chai": "^4.1.2"
}
}
.meteor/packages
# Meteor packages used by this project, one per line.
# Check this file (and the other files in this directory) into your repository.
#
# 'meteor add' and 'meteor remove' will edit this file for you,
# but you can also edit it by hand.
meteor-base#1.4.0 # Packages every Meteor app needs to have
mobile-experience#1.0.5 # Packages for a great mobile UX
mongo#1.6.0 # The database Meteor supports right now
reactive-var#1.0.11 # Reactive variable for tracker
tracker#1.2.0 # Meteor's client-side reactive programming library
standard-minifier-css#1.5.0 # CSS minifier run for production mode
standard-minifier-js#2.4.0 # JS minifier run for production mode
es5-shim#4.8.0 # ECMAScript 5 compatibility for older browsers
ecmascript#0.12.0 # Enable ECMAScript2015+ syntax in app code
shell-server#0.4.0 # Server-side component of the `meteor shell` command
react-meteor-data
accounts-ui#1.3.1
accounts-password#1.5.1
meteortesting:mocha
twbs:bootstrap
static-html
jquery
kadira:flow-router
kadira:blaze-layout
dburles:collection-helpers
accounts-base#1.4.3
alanning:roles
fortawesome:fontawesome
meteortoys:allthings
check#1.3.1
aldeed:collection2-core
sach:flow-db-admin
aldeed:simple-schema
server/main.js
import { Meteor } from 'meteor/meteor';
// import '../imports/startup/accounts-config.js';
import '../imports/routes.js';
import '../imports/schemas.js';
// import '../imports/startup/admin-config.js';
Meteor.startup(() => {
/*
*/
AdminConfig = {
collections: {
Posts: {}
}
};
});
client/main.js
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import '../imports/startup/accounts-config.js';
import '../imports/routes.js';
import '../imports/schemas.js';
// import '../imports/startup/admin-config.js';
Meteor.startup(() => {
/*
*/
AdminConfig = {
collections: {
Posts: {}
}
};
});
imports/schemas.js
import React from 'react';
// import { FlowRouter } from 'meteor/kadira:flow-router'
import { mount } from 'react-mounter';
import SimpleSchema from 'simpl-schema';
SimpleSchema.extendOptions(['autoform']);
Schemas = {};
Posts = new Meteor.Collection('posts');
Users = Meteor.users;
Schemas.Posts = new SimpleSchema({
title: {
label: 'Title',
type: String,
max: 60
},
content: {
label: 'Content',
type: String,
autoform: {
rows: 5
}
},
createdAt: {
type: Date,
label: 'Date',
autoValue: function () {
if (this.isInsert) {
return new Date();
}
}
},
owner: {
label: 'Author',
type: String,
regEx: SimpleSchema.RegEx.Id,
autoValue: function () {
if (this.isInsert) {
return Meteor.userId();
}
},
autoform: {
options: function () {
return _.map(Meteor.users.find().fetch(), function (user) {
return {
label: user.emails[0].address,
value: user._id
};
});
}
}
}
});
Posts.attachSchema(Schemas.Posts);
Then after launching, it shows the below; the validation doesn't work and the labels are not displayed also.
Please help

Uncaught (in promise): Error: StaticInjectorError[Service]

I am new to angular. I have created an webapplication using vs2015 and latest angular packages.
When i try to call my service from component on button click event then i am getting below error in browser console window.
Error: -
ERROR Error: Uncaught (in promise): Error: StaticInjectorError[ViewCountService]:
StaticInjectorError[ViewCountService]:
NullInjectorError: No provider for ViewCountService!
Error: StaticInjectorError[ViewCountService]:
StaticInjectorError[ViewCountService]:
NullInjectorError: No provider for ViewCountService!
at _NullInjector.get (injector.js:31)
at resolveToken (injector.js:387)
at tryResolveToken (injector.js:330)
at StaticInjector.get (injector.js:170)
at resolveToken (injector.js:387)
at tryResolveToken (injector.js:330)
at StaticInjector.get (injector.js:170)
at resolveNgModuleDep (ng_module.js:103)
at NgModuleRef_.get (refs.js:1037)
at resolveDep (provider.js:455)
at _NullInjector.get (injector.js:31)
at resolveToken (injector.js:387)
at tryResolveToken (injector.js:330)
at StaticInjector.get (injector.js:170)
at resolveToken (injector.js:387)
at tryResolveToken (injector.js:330)
at StaticInjector.get (injector.js:170)
at resolveNgModuleDep (ng_module.js:103)
at NgModuleRef_.get (refs.js:1037)
at resolveDep (provider.js:455)
at resolvePromise (zone.js:824)
at resolvePromise (zone.js:795)
at zone.js:873
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (ng_zone.js:575)
at ZoneDelegate.invokeTask (zone.js:424)
at Zone.runTask (zone.js:192)
at drainMicroTaskQueue (zone.js:602)
at ZoneTask.invokeTask [as invoke] (zone.js:503)
at invokeTask (zone.js:1540)
defaultErrorLogger # errors.js:48
ErrorHandler.handleError # error_handler.js:90
next # application_ref.js:311
schedulerFn # event_emitter.js:156
SafeSubscriber.__tryOrUnsub # Subscriber.ts:254
SafeSubscriber.next # Subscriber.ts:204
Subscriber._next # Subscriber.ts:135
Subscriber.next # Subscriber.ts:95
Subject.next # Subject.ts:61
EventEmitter.emit # event_emitter.js:131
(anonymous) # ng_zone.js:605
ZoneDelegate.invoke # zone.js:392
Zone.run # zone.js:142
NgZone.runOutsideAngular # ng_zone.js:404
onHandleError # ng_zone.js:605
ZoneDelegate.handleError # zone.js:396
Zone.runGuarded # zone.js:158
_loop_1 # zone.js:702
api.microtaskDrainDone # zone.js:711
drainMicroTaskQueue # zone.js:610
ZoneTask.invokeTask # zone.js:503
invokeTask # zone.js:1540
globalZoneAwareCallback # zone.js:1566
my app.module.ts: -
import { NgModule, Injectable } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule } from '#angular/http';
import { ModalModule } from 'ngx-modialog';
import { BootstrapModalModule, Modal, bootstrap4Mode } from 'ngx-modialog/plugins/bootstrap';
import { AppComponent } from './app.component';
import { ExportToPdfComponent } from './exportTopdf/exportTopdf.component';
import { InvalidPageComponent } from './invalidPage/invalidPage.component';
import { ViewCountService } from './Service/viewsCount.component';
const appRoutes: Routes = [
{ path: 'home', component: AppComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'export', component: ExportToPdfComponent },
{ path: '**', component: InvalidPageComponent }
];
#NgModule({
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot(appRoutes),
ModalModule.forRoot(),
BootstrapModalModule
],
declarations: [
AppComponent,
ExportToPdfComponent,
InvalidPageComponent
],
bootstrap: [
AppComponent
],
providers: [
ViewCountService
]
})
export class AppModule { }
exportTopdf.component.ts file: -
import { Component, ViewContainerRef, ViewEncapsulation } from '#angular/core';
import { ViewCountService } from '../Service/ViewsCount.component';
import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';
#Component({
selector: 'export-to-pdf',
templateUrl: 'app/exportTopdf/exportTopdf.component.html',
})
export class ExportToPdfComponent {
name: string;
fields: any;
constructor(public modal: Modal, private ViewCountService: ViewCountService) {
debugger;
this.fields = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
}
getViewCount(): void {
debugger;
this.ViewCountService.getViewCount()
.then(data => {
this.name = data;
console.log("I CANT SEE DATA HERE: ", this.name)
});
}
}
my service code: -
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class ViewCountService {
constructor(private http: Http) {
}
getViewCount() {
return this.http.get('api/Tableau/GetViewsCount')
.map(response => response.json() as string).toPromise();
}
getDataObservable(url: string) {
return this.http.get('api/Tableau/GetViewsCount')
.map(data => {
data.json();
console.log("I CAN SEE DATA HERE: ", data.json());
});
}
}
system.config.js: -
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
transpiler: 'typescript',
//typescript compiler options
typescriptOptions: {
emitDecoratorMetadata: true
},
paths: {
// paths serve as alias
'npm:': '/node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ngx-modialog': 'npm:ngx-modialog/bundle/ngx-modialog.umd.min.js',
'ngx-modialog/plugins/bootstrap': 'npm:ngx-modialog/plugins/bootstrap/bundle/ngx-modialog-bootstrap.umd.min.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
defaultExtension: 'js',
meta: {
'./*.js': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
package.json: -
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"build:e2e": "tsc -p e2e/",
"serve": "lite-server -c=bs-config.json",
"serve:e2e": "lite-server -c=bs-config.e2e.json",
"prestart": "npm run build",
"start": "concurrently \"npm run build:watch\" \"npm run serve\"",
"pree2e": "npm run build:e2e",
"e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
"preprotractor": "webdriver-manager update",
"protractor": "protractor protractor.config.js",
"pretest": "npm run build",
"test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
"pretest:once": "npm run build",
"test:once": "karma start karma.conf.js --single-run",
"lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"#angular/common": "~5.0.3",
"#angular/compiler": "~5.0.3",
"#angular/core": "~5.0.3",
"#angular/forms": "~5.0.3",
"#angular/http": "~5.0.3",
"#angular/platform-browser": "~5.0.3",
"#angular/platform-browser-dynamic": "~5.0.3",
"#angular/router": "~5.0.3",
"angular-in-memory-web-api": "~0.5.1",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"ngx-modialog": "^5.0.0",
"rxjs": "5.5.2",
"systemjs": "0.20.19",
"zone.js": "^0.8.4"
},
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
"typescript": "~2.6.1",
"canonical-path": "0.0.2",
"tslint": "^5.8.0",
"lodash": "^4.16.4",
"jasmine-core": "~2.8.0",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.2.0",
"rimraf": "^2.5.4",
"#types/node": "^8.0.53",
"#types/jasmine": "2.8.2"
},
"repository": {}
}
Thanks in advance for your valuable feedbacks and comments.
Look at your impors
app.module.ts
import { ViewCountService } from './Service/viewsCount.component';
exportTopdf.component.ts
import { ViewCountService } from '../Service/ViewsCount.component';
Since Systemjs is case-sensitive(See Service instance is not available for child component in angular2)
looks like you're importing different modules
ViewsCount
|
viewsCount
So choose only one option to import your service
app.module.ts
import { ViewCountService } from './Service/viewsCount.component';
exportTopdf.component.ts
import { ViewCountService } from '../Service/viewsCount.component';
^
instead of V
Read also style guide to better understanding how to name your files
If you are using Angular 4.3+ until 5 you will need to import HttpClient in your app.module from the new library
> import { HttpClientModule } from '#angular/common/http';
imports: [
YModule,
XModule,
HttpClientModule
],
In your service :
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class ViewCountService {
constructor(private http: HttpClient ) {
}
getViewCount() {
return this.http.get('api/Tableau/GetViewsCount');
}
...
}
In your component:
getViewCount(): void {
this.ViewCountService.getViewCount()
.subscribe(
data =>{console.log(data);//your data},
err=>{console.log(err);},
() => {console.log("Done loading");}
);
}
I was facing the same issue then I have added below line in app.module and it worked for me.
import { HttpClientModule } from ‘#angular/common/http’;
And add it to the
#NgModule({ imports: [ ..., HttpClientModule,... ]
It doesn't look to be solved yet:
https://github.com/angular/angular/issues/20339
As a work around, try to make all your constructor() functions without parameters by extracting the as properties.
ExportToPdfComponent:
import { Component, ViewContainerRef, ViewEncapsulation } from '#angular/core';
import { ViewCountService } from '../Service/ViewsCount.component';
import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';
#Component({
selector: 'export-to-pdf',
templateUrl: 'app/exportTopdf/exportTopdf.component.html',
})
export class ExportToPdfComponent {
name: string;
fields: any;
modal: Modal;
ViewCountService: ViewCountService;
constructor() {
debugger;
this.fields = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
}
getViewCount(): void {
debugger;
this.ViewCountService.getViewCount()
.then(data => {
this.name = data;
console.log("I CANT SEE DATA HERE: ", this.name)
});
}
}
ViewCountService:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class ViewCountService {
private http: Http;
constructor() {
}
getViewCount() {
return this.http.get('api/Tableau/GetViewsCount')
.map(response => response.json() as string).toPromise();
}
getDataObservable(url: string) {
return this.http.get('api/Tableau/GetViewsCount')
.map(data => {
data.json();
console.log("I CAN SEE DATA HERE: ", data.json());
});
}
}
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
routing
],
add this into your app.module.ts file

Resources