Nuxt, Vue, RefreshToken => Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined => Axios plugin, Axios Interceptors - vuejs2

my goal is to refresh the token after catching the 401 status code and the "token expired" message in my interceptor on the response ...
What are they doing wrong?
I'm using nuxt, vue, axios. Please help!
Uncaught (in promise) TypeError: Cannot read property 'protocol' of
undefined
it sends me back to that code:
#/plugins/axios.js:
import Vue from 'vue';
import axios from 'axios';
axios.interceptors.response.use((response) => {
console.debug("AXIOS.JS plugin => response: ", response);
return response;
}, function (error) {
console.debug("AXIOS.JS plugin => error: ", error);
return Promise.reject(error);
});
Vue.use(axios);
package.json:
{
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"dependencies": {
"#nuxtjs/axios": "^5.13.1",
"#nuxtjs/composition-api": "^0.24.7",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/proxy": "^2.1.0",
"#nuxtjs/pwa": "^3.3.5",
"#vue/composition-api": "^1.0.0-rc.13",
"core-js": "^3.9.1",
"nuxt": "^2.15.6",
"vue-multiselect": "^2.1.6",
"vue2-datepicker": "^3.9.1"
},
"devDependencies": {
"#nuxtjs/tailwindcss": "^4.1.2",
"autoprefixer": "^10.2.5",
"postcss": "^8.3.0",
"tailwindcss": "^2.1.2"
}
}
nuxt.config.js
const routes = require('./routes/index.js')
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'Fokser',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
{
//src: "https://skrypt-cookies.pl/id/d6458d5064c23515.js",
//src: "https://skrypt-cookies.pl/id/69205d8cab854dc2.js",
body: true,
},
],
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
'#/static/css/styles.css',
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{
src: "#/plugins/filters.js",
src: "#/plugins/axios.js",
}
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/tailwindcss
'#nuxtjs/tailwindcss',
'#nuxtjs/composition-api/module'
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/proxy',
'#nuxtjs/dotenv'
],
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
proxy: true
},
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
lang: 'en'
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
},
proxy: {
'/api/': {
target: process.env.VUE_APP_ROOT_API,
pathRewrite: { '^/api': '' }
}
},
router: {
extendRoutes(nuxtRoutes, resolve) {
routes.forEach((route) => {
nuxtRoutes.push({
name: route.name,
path: route.path,
component: resolve(__dirname, route.component)
})
})
}
}
}
This occurs at main page (localhost):
besides, I am making a request to api like:
loadUserInfo({ commit }) {
let token = localStorage.getItem("auth_token");
let userId = localStorage.getItem("id");
commit("setUserToken", token);
commit("setUserId", userId);
if (userId && token) {
this.$axios.get(`api/accounts/userName/${userId}`)
.then((res) => {
if (res.status === 200) {
commit("setUserName", res.data.userName);
}
})
.catch(err => {
console.debug("[authorize.js LoadUserInfo], errors: ", err);
})
}
},
async getRecords({commit}, request) {
let config = {
params: {
recordType: request.recordType,
limit: limit
},
}
return await this.$axios.get(`/api/records/getRecords`, config);
}
loadAll({ commit }, request) {
this.$axios.get(`/api/records/all`, request)
.then((res) => {
if (res.status === 200) {
commit('setRecords', res.data);
}
});
},
I don't know where is the problem... :(

Related

Mobx statechange not detected

I have a small simple setup. With mobx and preact.
class AppStore {
loadingobjects = true;
constructor() {
makeObservable(this, {
loadingobjects: observable,
});
this.fetchCommonObjects();
}
fetchCommonObjects = () => {
window
.fetch(url)
.then((res) => res.json())
.then((json) => {
/* data processing */
this.loadingobjects = false;
});
};
}
export const AppStoreContext = createContext();
function AppStoreProvider({ children }) {
return (
<AppStoreContext.Provider value={new AppStore()}>
{children}
</AppStoreContext.Provider>
);
}
export default AppStoreProvider;
export default function useAppStore() {
return useContext(AppStoreContext);
}
const List = observer(() => {
const store = useAppStore();
if (store.loadingobjects) {
return <div class="ui active centered inline loader"></div>;
} else {
return (page content);
}
});
problem is that store.loadingobjects Is always false. Seems like im doing something wrong but i cant put my finger on it...
What am i missing or doing wrong?
Edit addding my configs:
package.json
{
"name": "project",
"version": "0.0.2",
"license": "MIT",
"scripts": {
"start": "set NODE_ENV=dev && webpack serve --mode=development",
"build": "set NODE_ENV=production && webpack -p",
},
"devDependencies": {
"#babel/core": "^7.20.12",
"#babel/plugin-transform-runtime": "^7.19.6",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.2",
"babel-plugin-import": "^1.13.6",
"html-webpack-plugin": "^5.5.0",
"surge": "^0.19.0",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.11.1"
},
"dependencies": {
"#babel/polyfill": "^7.12.1",
"mobx": "^6.7.0",
"mobx-react": "^7.6.0",
"preact": "^10.11.3"
}
}
webpack.config.js
const path = require('path');
const isProd = (process.env.NODE_ENV === 'production');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
//input
entry: ["#babel/polyfill",'./src'],
resolve: {
alias:{
"react": "preact/compat",
"react-dom": "preact/compat",
"react/jsx-runtime": "preact/jsx-runtime"
}
},
//output
output: {
path : path.join(__dirname, 'build'),
filename : 'bundle.js'
},
//transformations
module: {
rules : [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
}
]
},
//sourcemaps
devtool: 'source-map',
plugins: [new HtmlWebpackPlugin({
template: './src/index.html',
favicon: "./src/favicon.ico"
})],
//server
devServer: {
compress: true,
historyApiFallback: true
}
}
.babelrc
{
"presets": ["#babel/preset-react", ["#babel/preset-env", {"useBuiltIns": "usage",}]],
"plugins": [
["#babel/plugin-transform-runtime"],
[
"#babel/plugin-transform-react-jsx",
{
"pragma": "h",
"pragmaFrag": "Fragment"
}
]
]
}
I found the issue. I started cutting the components into smaller pieces and then adding and removing them into the component hierarchy until i found the component causing the issue. It turned out that i had done onClick={method()} and this was changeing state causing the endless rerenders.

missing js files from _nuxt folder

i'm using nuxt 2.15.4 and I suddenly got a very odd issue. my code was working fine (actually still working fine on local <--dev & build--> ) but now on server after build it wont be loaded correctly and I get these errors : GET https://example.com/_nuxt/8bab19f.js net::ERR_ABORTED 404 (Not Found) . what is wrong? actually I have two clones of my app on other server and they works fine! can it be because of bundle size warnings on build? if so how can I reduce bundle size (practical answers with examples plz ;) )??
//nuxt.config.js
import colors from 'vuetify/es5/util/colors'
const env = require('dotenv').config()
const webpack = require('webpack')
export default {
telemetry: false,
srcDir: process.env.THEME_CUSTOMIZE === 'true' ? 'src/themes/customs/' : 'src/themes/'+process.env.THEME+'/',
loading: {
color: 'green',
failedColor: 'red',
height: '3px'
},
router: {
},
head: {
title: process.env.SITE_TITLE + ' | ' + process.env.SITE_SHORT_DESC || '',
htmlAttrs: {
lang: process.env.SITE_LANGUAGE || 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'keywords', name: 'keywords', content: process.env.SITE_KEYWORDS || '' },
{ hid: 'description', name: 'description', content: process.env.SITE_DESCRIPTION || '' },
{ hid: 'robots', name: 'robots', content: process.env.SITE_ROBOTS || '' },
{ hid: 'googlebot', name: 'googlebot', content: process.env.SITE_GOOGLE_BOT || '' },
{ hid: 'bingbot', name: 'bingbot', content: process.env.SITE_BING_BOT || '' },
{ hid: 'og:locale', name: 'og:locale', content: process.env.SITE_OG_LOCALE || '' },
{ hid: 'og:type', name: 'og:type', content: process.env.SITE_OG_TYPE || '' },
{ hid: 'og:title', name: 'og:title', content: process.env.SITE_OG_TITLE || '' },
{ hid: 'og:description', name: 'og:description', content: process.env.SITE_OG_DESCRIPTION || '' },
{ hid: 'og:url', name: 'og:url', content: process.env.SITE_BASE_URL || '' },
{ hid: 'og:site_name', name: 'og:site_name', content: process.env.SITE_OG_SITENAME || '' },
{ hid: 'theme-color', name: 'theme-color', content: process.env.SITE_THEME_COLOR || '' },
{ hid: 'msapplication-navbutton-color', name: 'msapplication-navbutton-color', content: process.env.SITE_MSAPP_NAVBTN_COLOR || '' },
{ hid: 'apple-mobile-web-app-status-bar-style', name: 'apple-mobile-web-app-status-bar-style', content: process.env.SITE_APPLE_WM_STATUSBAR_STYLE || '' },
{ hid: 'X-UA-Compatible', 'http-equiv': 'X-UA-Compatible', content: process.env.SITE_X_UA_Compatible || '' },
{ hid: 'google-site-verification', name:'google-site-verification', content: '' },
{ hid: 'enamad' , name: 'enamad' , content: process.env.ENAMAD_META},
{ hid: 'samandehi' , name: 'samandehi' , content: process.env.SAMANDEHI_META},
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: process.env.SITE_FAVICON },
{ rel: 'canonical', href: process.env.SITE_BASE_URL },
]
},
css: [
'~/assets/scss/vuetify.scss',
'~/assets/scss/style.scss',
'#mdi/font/css/materialdesignicons.css',
'font-awesome/css/font-awesome.min.css',
'#fortawesome/fontawesome-free/css/all.css',
'~/assets/scss/media.scss',
'~/assets/scss/customization.scss',
'~/assets/scss/sweetalert.scss',
'~/assets/scss/noty.scss',
'~/assets/scss/flipclock.scss',
'~/assets/scss/sorting.scss',
'~/assets/scss/cropper.scss',
'~/assets/scss/transitions.scss',
'~/assets/scss/product-zoom.scss',
'swiper/css/swiper.css',
],
plugins: [
'plugins/mixins/reqerrors.js',
'plugins/mixins/user.js',
'plugins/mixins/language.js',
'plugins/mixins/shopinfo.js',
'plugins/mixins/formattedprice.js',
'plugins/mixins/utils.js',
'plugins/mixins/cms.js',
'plugins/mixins/client.js',
'plugins/mixins/cart.js',
'plugins/axios.js',
'plugins/veevalidate.js',
'plugins/noty.js',
'#plugins/vuedraggable',
'#plugins/vuedraggable',
{src: 'plugins/vuepersiandatepicker.js', mode: 'client'},
{src: 'plugins/cropper.js', mode: 'client'},
{src: 'plugins/vue-product-zoomer.js', mode: 'client'},
{src: 'plugins/vueeditor.js', mode: 'client'},
{src: 'plugins/nuxt-swiper-plugin.js', mode: 'client' }
],
buildModules: [
'#nuxtjs/dotenv',
'#nuxtjs/vuetify',
'#nuxtjs/device',
'nuxt-gsap-module',
],
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth',
['vue-sweetalert2/nuxt',
{
confirmButtonColor: '#29BF12',
cancelButtonColor: '#FF3333'
}
],
'cookie-universal-nuxt',
'#nuxtjs/gtm',
'#nuxtjs/google-gtag'
],
device: {
refreshOnResize: true
},
gtm: {
id: process.env.GOOGLE_TAGS_ID,
debug: false,
},
'google-gtag': {
id: process.env.GOOGLE_ANALYTICS_ID,
debug: false,
},
dotenv: {
path: './'
},
gsap: {
extraPlugins: {
cssRule: false,
draggable: false,
easel: false,
motionPath: false,
pixi: false,
text: false,
scrollTo: false,
scrollTrigger: false
},
extraEases: {
expoScaleEase: false,
roughEase: false,
slowMo: true,
}
},
axios: {
baseURL: process.env.API_BASE_URL,
},
auth: {
strategies: {
local: {
endpoints: {
login: { url: 'auth/login', method: 'post', propertyName: 'token' },
logout: { url: 'auth/logout', method: 'post' },
user: { url: 'auth/info', method: 'get', propertyName: '' }
}
}
},
redirect: {
login: '/login',
home: '',
logout: '/login'
},
cookie: {
prefix: 'auth.',
options: {
path: '/',
maxAge: process.env.AUTH_COOKIE_MAX_AGE
}
}
},
publicRuntimeConfig: {
gtm: {
id: process.env.GOOGLE_TAGS_ID
},
'google-gtag': {
id: process.env.GOOGLE_ANALYTICS_ID,
}
},
vuetify:{
rtl: process.env.SITE_DIRECTION === 'rtl' ? true : false ,
customVariables: ['~/assets/scss/variables_vuetify.scss'],
breakpoint: {
thresholds: {
xs: 600,
sm: 960,
md: 1366,
lg: 1920,
},
},
icons: {
iconfont: 'mdi',
},
treeShake: true,
theme: {
dark: false,
themes: {
dark: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3
}
}
}
},
build: {
transpile: ['vee-validate/dist/rules'],
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery',
jQuery: "jquery",
"window.jQuery": "jquery",
'_': 'lodash'
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
postcss: {
preset: {
features: {
customProperties: false,
},
},
},
babel:{
plugins: [
['#babel/plugin-proposal-private-methods', { loose: true }]
]
},
loaders: {
scss: {
additionalData: `
$direction:${process.env.SITE_DIRECTION};
$lang:${process.env.SITE_LANGUAGE};
$theme_body_color:${process.env.THEME_BODY_COLOR};
$theme_main_color:${process.env.THEME_MAIN_COLOR};
$theme_main_color2:${process.env.THEME_MAIN_COLOR2};
$theme_side_color:${process.env.THEME_SIDE_COLOR};
$theme_side_color2:${process.env.THEME_SIDE_COLOR2};
$theme_link_color:${process.env.THEME_LINK_COLOR};
`
}
},
}
}
package.json
{
"name": "nuxt",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"dependencies": {
"#nuxtjs/auth": "^4.9.1",
"#nuxtjs/axios": "^5.13.1",
"#nuxtjs/device": "^2.1.0",
"#nuxtjs/google-gtag": "^1.0.4",
"#nuxtjs/gtm": "^2.4.0",
"chart.js": "^2.9.3",
"cookie-universal-nuxt": "^2.1.4",
"core-js": "^3.9.1",
"jquery": "^3.5.1",
"nuxt": "2.15.4",
"swiper": "^5.4.5",
"v-viewer": "^1.5.1",
"vee-validate": "^3.3.7",
"vue-awesome-swiper": "^4.1.1",
"vue-chartjs": "^3.5.0",
"vue-cropperjs": "^4.1.0",
"vue-easy-dnd": "^1.10.2",
"vue-persian-datetime-picker": "^2.2.0",
"vue-product-zoomer": "^3.0.1",
"vue-sweetalert2": "^4.2.1",
"vue2-editor": "^2.10.2",
"vuedraggable": "^2.24.0"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.15.1",
"#mdi/font": "^5.9.55",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "1.11.3",
"flipclock": "^0.10.8",
"font-awesome": "^4.7.0",
"noty": "^3.2.0-beta",
"nuxt-gsap-module": "^1.2.1",
"sass": "1.32.13"
}
}
Some things that may be improved in your nuxt.config.js configuration:
const env = require('dotenv').config() is not needed because it is already baked into Nuxt
not an issue but rather a style, use es6 template literals for interpolation, it is more readable
your google-site-verification is hardcoded, probably not wanted
you do have a LOT of things into your css property, I'm pretty sure that you don't need all of them on every single page. So you could call them only when needed and have a global.scss file to make it a bit more ordered for the remaining (mandatory) global CSS
same goes for plugins, a lot of things there (#plugins/vuedraggable is written twice)
mixins should not be in plugins but loaded per component, and are actually deprecated in Vue3
#nuxtjs/dotenv should be removed from buildModules and package.json
you should remove some options in your gsap key because the default options are already the ones that you're passing, just keep slowMo
axios should be configured by using runtimeConfigs as explained here: https://stackoverflow.com/a/67983038/8816585
your auth key probably works with URL like auth/login but I'd probably be sure that this is fine with something like /auth/login
vuetify's RTL is dictated by an env variable? Should be dynamic and depending of the HTML IMO
plugin-proposal-private-methods was a pretty ugly fix, it was fixed at 2.15.5 but because of security reasons, I'd rather update it to 2.15.7
not sure what are the scss loaders but I think that this can be dynamic with "CSS variables"
I'm not sure how you are actually loading lodash, I just hope that you are not bringing the whole library when you're actually only using only a few methods
and of course, in my opinion, I'll ditch jQuery totally when using Vue because it's not useful when using this framework, at all.

nuxt vuetify gives SassError: Expected identifier

I'm using Nuxt 2.15.4 and nuxt/vuetify 1.11.3
my project was working fine, but when i move it to a new server at build I got these errors:
this is my package.json file
{
"name": "myproject",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"dependencies": {
"#nuxtjs/auth": "^4.9.1",
"#nuxtjs/axios": "^5.13.1",
"#nuxtjs/device": "^2.1.0",
"#nuxtjs/google-gtag": "^1.0.4",
"#nuxtjs/gtm": "^2.4.0",
"chart.js": "^2.9.3",
"cookie-universal-nuxt": "^2.1.4",
"core-js": "^3.9.1",
"jquery": "^3.5.1",
"nuxt": "^2.15.3",
"swiper": "^5.4.5",
"v-viewer": "^1.5.1",
"vee-validate": "^3.3.7",
"vue-awesome-swiper": "^4.1.1",
"vue-chartjs": "^3.5.0",
"vue-cropperjs": "^4.1.0",
"vue-easy-dnd": "^1.10.2",
"vue-glide-js": "^1.3.14",
"vue-persian-datetime-picker": "^2.2.0",
"vue-product-zoomer": "^3.0.1",
"vue-slick-carousel": "^1.0.6",
"vue-sweetalert2": "^4.2.1",
"vue2-editor": "^2.10.2",
"vuedraggable": "^2.24.0"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.15.1",
"#mdi/font": "^5.9.55",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "1.11.3",
"flipclock": "^0.10.8",
"font-awesome": "^4.7.0",
"noty": "^3.2.0-beta",
"nuxt-gsap-module": "^1.2.1",
"css-loader": "^5.0.0",
"sass-loader": "^10.1.1",
"less-loader": "^6.1.2"
}
}
and my nuxt.config
import colors from 'vuetify/es5/util/colors'
const env = require('dotenv').config()
const webpack = require('webpack')
export default {
telemetry: false,
loading: {
color: 'green',
failedColor: 'red',
height: '3px'
},
// serverMiddleware: ['~/api/index.js'],
router: {
// base: process.env.NUXT_BASE_URL || '/'
},
/*
** Headers of the page
** See https://nuxtjs.org/api/configuration-head
*/
head: {
// titleTemplate: '%s - ' + process.env.npm_package_name,
// title: process.env.npm_package_name || '',
// titleTemplate: '%s - ' + process.env.SITE_TITLE,
title: process.env.SITE_TITLE + ' | ' + process.env.SITE_SHORT_DESC || '',
htmlAttrs: {
lang: process.env.SITE_LANGUAGE || 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'keywords', name: 'keywords', content: process.env.SITE_KEYWORDS || '' },
{ hid: 'description', name: 'description', content: process.env.SITE_DESCRIPTION || '' },
{ hid: 'robots', name: 'robots', content: process.env.SITE_ROBOTS || '' },
{ hid: 'googlebot', name: 'googlebot', content: process.env.SITE_GOOGLE_BOT || '' },
{ hid: 'bingbot', name: 'bingbot', content: process.env.SITE_BING_BOT || '' },
{ hid: 'og:locale', name: 'og:locale', content: process.env.SITE_OG_LOCALE || '' },
{ hid: 'og:type', name: 'og:type', content: process.env.SITE_OG_TYPE || '' },
{ hid: 'og:title', name: 'og:title', content: process.env.SITE_OG_TITLE || '' },
{ hid: 'og:description', name: 'og:description', content: process.env.SITE_OG_DESCRIPTION || '' },
{ hid: 'og:url', name: 'og:url', content: process.env.SITE_BASE_URL || '' },
{ hid: 'og:site_name', name: 'og:site_name', content: process.env.SITE_OG_SITENAME || '' },
{ hid: 'theme-color', name: 'theme-color', content: process.env.SITE_THEME_COLOR || '' },
{ hid: 'msapplication-navbutton-color', name: 'msapplication-navbutton-color', content: process.env.SITE_MSAPP_NAVBTN_COLOR || '' },
{ hid: 'apple-mobile-web-app-status-bar-style', name: 'apple-mobile-web-app-status-bar-style', content: process.env.SITE_APPLE_WM_STATUSBAR_STYLE || '' },
{ hid: 'X-UA-Compatible', 'http-equiv': 'X-UA-Compatible', content: process.env.SITE_X_UA_Compatible || '' },
{ hid: 'google-site-verification', name:'google-site-verification', content: 'T_NpyOb-VoAjaAcnhB8b9MTslHVfhtfcLNf2dvBtlfI' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: process.env.SITE_FAVICON },
// { rel: 'shortcut icon', type: 'image/x-icon', href: process.env.SITE_FAVICON },
{ rel: 'canonical', href: process.env.SITE_BASE_URL },
// { rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/npm/font-awesome#4.x/css/font-awesome.min.css' },
]
},
/*
** Global CSS
*/
css: [
'~/assets/scss/vuetify.scss',
'~/assets/scss/style.scss',
'#mdi/font/css/materialdesignicons.css',
'font-awesome/css/font-awesome.min.css',
'#fortawesome/fontawesome-free/css/all.css',
'~/assets/scss/media.scss',
'~/assets/scss/customization.scss',
'~/assets/scss/sweetalert.scss',
'~/assets/scss/noty.scss',
'~/assets/scss/flipclock.scss',
'~/assets/scss/glide.scss',
'~/assets/scss/sorting.scss',
'~/assets/scss/cropper.scss',
'~/assets/scss/transitions.scss',
'~/assets/scss/product-zoom.scss',
'vue-slick-carousel/dist/vue-slick-carousel.css',
'swiper/css/swiper.css',
],
/*
** Plugins to load before mounting the App
** https://nuxtjs.org/guide/plugins
*/
plugins: [
'plugins/mixins/reqerrors.js',
'plugins/mixins/user.js',
'plugins/mixins/language.js',
'plugins/mixins/shopinfo.js',
'plugins/mixins/formattedprice.js',
'plugins/mixins/utils.js',
'plugins/mixins/cms.js',
'plugins/mixins/client.js',
'plugins/mixins/cart.js',
'plugins/axios.js',
'plugins/veevalidate.js',
'plugins/noty.js',
'plugins/glide.js',
'#plugins/vuedraggable',
'#plugins/vuedraggable',
'#plugins/vue-slick-carousel.js',
{src: 'plugins/vuepersiandatepicker.js', mode: 'client'},
{src: 'plugins/cropper.js', mode: 'client'},
{src: 'plugins/vue-product-zoomer.js', mode: 'client'},
{src: 'plugins/vueeditor.js', mode: 'client'},
{src: 'plugins/nuxt-swiper-plugin.js', mode: 'client' }
],
// Auto import components: https://go.nuxtjs.dev/config-components
// components: true,
/*
** Nuxt.js dev-modules
*/
buildModules: [
'#nuxtjs/dotenv',
'#nuxtjs/vuetify',
'#nuxtjs/device',
'nuxt-gsap-module',
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
// Doc: https://auth.nuxtjs.org/guide/
'#nuxtjs/auth',
// Doc: https://sweetalert2.github.io/
['vue-sweetalert2/nuxt',
{
confirmButtonColor: '#29BF12',
cancelButtonColor: '#FF3333'
}
],
'cookie-universal-nuxt',
'#nuxtjs/gtm',
'#nuxtjs/google-gtag',
],
device: {
// defaultUserAgent: 'Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Mobile Safari/537.36',
refreshOnResize: true
},
gtm: {
id: process.env.GOOGLE_TAGS_ID,
// enabled: undefined, /* see https://github.com/nuxt-community/gtm-module */
debug: false,
// layer: 'dataLayer',
// variables: {},
// pageTracking: false,
// pageViewEventName: 'nuxtRoute',
// autoInit: true,
// respectDoNotTrack: true,
// scriptId: 'gtm-script',
// scriptDefer: false,
// scriptURL: 'https://www.googletagmanager.com/gtm.js',
// crossOrigin: false,
// noscript: true,
// noscriptId: 'gtm-noscript',
// noscriptURL: 'https://www.googletagmanager.com/ns.html'
},
'google-gtag': {
id: process.env.GOOGLE_ANALYTICS_ID,
// config: {
// anonymize_ip: true, // anonymize IP
// send_page_view: false, // might be necessary to avoid duplicated page track on page reload
// linker: {
// domains: ['domain.com','domain.org']
// }
// },
debug: false, // enable to track in dev mode
// disableAutoPageTrack: false, // disable if you don't want to track each page route with router.afterEach(...).
// additionalAccounts: [{
// id: 'AW-XXXX-XX', // required if you are adding additional accounts
// config: {
// send_page_view: false // optional configurations
// }
// }]
},
dotenv: {
/* module options */
},
gsap: {
extraPlugins: {
cssRule: false,
draggable: false,
easel: false,
motionPath: false,
pixi: false,
text: false,
scrollTo: false,
scrollTrigger: false
},
extraEases: {
expoScaleEase: false,
roughEase: false,
slowMo: true,
}
},
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
baseURL: process.env.API_BASE_URL,
},
/*
** Auth module configuration
** See https://auth.nuxtjs.org/options
*/
auth: {
strategies: {
local: {
endpoints: {
login: { url: 'auth/login', method: 'post', propertyName: 'token' },
logout: { url: 'auth/logout', method: 'post' },
user: { url: 'auth/info', method: 'get', propertyName: '' }
}
}
},
redirect: {
login: '/login',
// callback: '/login',
home: '',
logout: '/login'
},
cookie: {
prefix: 'auth.',
options: {
path: '/',
maxAge: process.env.AUTH_COOKIE_MAX_AGE
}
}
},
publicRuntimeConfig: {
gtm: {
id: process.env.GOOGLE_TAGS_ID
},
'google-gtag': {
id: process.env.GOOGLE_ANALYTICS_ID,
}
},
vuetify:{
rtl: process.env.SITE_DIRECTION === 'rtl' ? true : false ,
customVariables: ['~/assets/scss/stylevariables.scss'],
icons: {
iconfont: 'mdi',
},
treeShake: true,
theme: {
dark: false,
themes: {
dark: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3
}
}
}
},
/*
** Build configuration
** See https://nuxtjs.org/api/configuration-build/
*/
build: {
transpile: ['vee-validate/dist/rules'],
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery',
jQuery: "jquery",
"window.jQuery": "jquery",
'_': 'lodash'
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
// postcss: {
// preset: {
// features: {
// customProperties: false,
// },
// },
// },
loaders: {
scss: {
additionalData: `
$theme_body_color:${process.env.THEME_BODY_COLOR};
$theme_main_color:${process.env.THEME_MAIN_COLOR};
$theme_main_color2:${process.env.THEME_MAIN_COLOR2};
$theme_side_color:${process.env.THEME_SIDE_COLOR};
$theme_side_color2:${process.env.THEME_SIDE_COLOR2};
$theme_link_color:${process.env.THEME_LINK_COLOR};
`
}
},
}
}
even when the new server got error, my localhost was working fine. then i deleted node_modules and package-lock.json and used npm i ; now my localhost is also has these errors
does anyone know what has caused the problem??
Installing npm install sass#1.32.8 fixes the issue for the time being. If you're using nuxt + yarn you might have to set this through the resolutions property in package.json, but in general this is the recommend solution: https://github.com/sass/dart-sass/issues/1287
The underlying cause is new versions of sass somehow taking issue with lines containing only whitespace.
In my case I also had to leave out the "^", otherwise npm install downloads version "1.32.10".
"sass": "1.32.8",
I get same error. & I changed sass-loader & less-loader dependencies to under versions. & add sass dependancy
In my package.json
"less": "^4.1.1",
"less-loader": "^2.0.0",
"sass": "1.32.8",
"sass-loader": "10.1.1",
had the same issue starting 2 days ago, tried going back a few versions on both Nuxtjs and Vuetify but nothing worked
Disabling treeshake did it for me, I hope this is temporary.
Thanks for the info.
Looks like it was caused by treeShake option in vuetify, so by removing it (or false) , every thing went back to normal.
*** UPDATE ***
Removing treeShake only works on dev and still gives error in npm run build. But treeShake: false works fine on both dev and build
// nuxt.config.js
vuetify:{
rtl: process.env.SITE_DIRECTION === 'rtl' ? true : false ,
customVariables: ['~/assets/scss/stylevariables.scss'],
icons: {
iconfont: 'mdi',
},
treeShake: false,
theme: {
dark: false,
themes: {
dark: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3
}
}
}
},
Update
finally turned on my treeShake and surprisingly work with "sass": "1.32.13" , "nuxt": "2.15.4", "#nuxtjs/vuetify": "1.11.3"

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 1 Error with React, Babel and Webpack

I am building a CRUD web application using Webpack, Express, Epilogue, Sequelize, Sqlite3 and React. After setting up Webpack and Babel, I can add entries to the database but not retrieve entries. When I add an entry, if I look at http://localhost:3000/blogposts (one of my endpoints) the page is blank, but in the server output I see my entries get added.
server output in the console
To retrieve entries from the database I use:
getPosts = async () => {
const response = await fetch('/blogposts');
const data = await response.json();
data.forEach(item => item.editMode = false);
this.setState({ data })
}
And I get the error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 1
full error message
I assume this is an error with babel/webpack and await/async.
my webpack.config.js:
const path = require("path")
const HtmlWebPackPlugin = require("html-webpack-plugin")
module.exports = {
entry: {
main: './src/index.js'
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
target: 'web',
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
},
]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./src/index.html",
excludeChunks: [ 'server' ]
})
],
resolve: {
extensions: ["*",".js", ".jsx", "json"],
alias: {
'components': path.resolve(__dirname, '/components')
}
},
}
my webpackserver.config.js:
const path = require('path')
const nodeExternals = require('webpack-node-externals')
module.exports = {
entry: {
server: './src/server/server.js',
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
target: 'node',
resolve: {
extensions: ['.js', '.jsx'],
alias: {
'components': path.resolve(__dirname, '/components')
}
},
node: {
__dirname: false,
__filename: false,
},
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
}
my server.js:
import path from 'path'
import express from 'express'
require('dotenv').config();
const cors = require('cors');
const bodyParser = require('body-parser');
const session = require('express-session');
const { ExpressOIDC } = require('#okta/oidc-middleware');
const Sequelize = require('sequelize');
const epilogue = require('epilogue'), ForbiddenError = epilogue.Errors.ForbiddenError;
const port = process.env.PORT || 3000
const app = express(),
DIST_DIR = __dirname,
HTML_FILE = path.join(DIST_DIR, '/src/index.html')
app.use(express.static(DIST_DIR))
app.get('*', (req, res) => {
res.sendFile(HTML_FILE)
})
// session support is required to use ExpressOIDC
app.use(session({
secret: process.env.RANDOM_SECRET_WORD,
resave: true,
saveUninitialized: false
}));
const oidc = new ExpressOIDC({
issuer: `${process.env.OKTA_ORG_URL}/oauth2/default`,
client_id: process.env.OKTA_CLIENT_ID,
client_secret: process.env.OKTA_CLIENT_SECRET,
redirect_uri: process.env.REDIRECT_URL,
scope: 'openid profile',
routes: {
callback: {
path: '/authorization-code/callback',
defaultRedirect: '/admin'
}
}
});
// ExpressOIDC will attach handlers for the /login and /authorization-code/callback routes
app.use(oidc.router);
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'src')));
app.get('/home', (req, res) => {
res.sendFile(path.join(__dirname, './home.html'));
});
app.get('/admin', oidc.ensureAuthenticated(), (req, res) => {
res.sendFile(path.join(__dirname, './admin.html'));
});
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/home');
});
console.log("redirect");
app.get('/', (req, res) => {
res.redirect('/home');
});
// //for each blog post
app.get('/lifestyle/:title', function (req, res) {
res.send('Blogpost template here!')
})
const database = new Sequelize({
dialect: 'sqlite',
storage: './db.sqlite',
operatorsAliases: false,
});
const Post = database.define('posts', {
title: Sequelize.STRING,
content: Sequelize.TEXT,
});
const blogPost = database.define('blogposts', {
title: Sequelize.STRING,
content: Sequelize.TEXT,
published: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false,
},
});
const test = database.define('test', {
title: Sequelize.STRING,
content: Sequelize.TEXT,
});
epilogue.initialize({ app, sequelize: database });
const PostResource = epilogue.resource({
model: Post,
endpoints: ['/posts', '/posts/:id'],
});
const blogPostResource = epilogue.resource({
model: blogPost,
endpoints: ['/blogposts', '/blogposts/:id'],
});
PostResource.all.auth(function (req, res, context) {
return new Promise(function (resolve, reject) {
resolve(context.continue);
})
});
database.sync().then(() => {
oidc.on('ready', () => {
app.listen(port, () => console.log(`My Blog App listening on port ${port}!`))
});
});
oidc.on('error', err => {
// An error occurred while setting up OIDC
console.log("oidc error: ", err);
});
my package.json:
{
"name": "blog",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"build": "rm -rf dist && webpack --mode development --config webpackserver.config.js && webpack --mode development",
"start": "node ./dist/server.js"
},
"proxy": "http://localhost:3000",
"author": "",
"license": "ISC",
"dependencies": {
"#okta/oidc-middleware": "1.0.2",
"D": "1.0.0",
"babel-polyfill": "6.26.0",
"babel-preset-es2015": "6.24.1",
"babel-preset-stage-0": "6.24.1",
"babel-runtime": "6.26.0",
"body-parser": "1.18.3",
"cors": "2.8.5",
"dotenv": "6.2.0",
"epilogue": "0.7.1",
"express": "4.16.4",
"express-session": "1.15.6",
"fibers": "4.0.2",
"node-sass": "4.13.0",
"rc": "1.2.8",
"sass": "1.23.7",
"sequelize": "4.44.3",
"sqlite3": "4.1.0",
"webpack-isomorphic-tools": "3.0.6"
},
"devDependencies": {
"#babel/core": "7.7.5",
"#babel/plugin-proposal-class-properties": "7.7.4",
"#babel/plugin-transform-runtime": "7.7.6",
"#babel/preset-env": "7.7.6",
"#babel/preset-react": "7.7.4",
"#material-ui/core": "4.7.2",
"#material-ui/icons": "4.5.1",
"babel-loader": "8.0.6",
"babel-plugin-transform-runtime": "6.23.0",
"babel-preset-env": "1.7.0",
"css-loader": "3.3.2",
"file-loader": "5.0.2",
"grommet": "2.9.0",
"html-loader": "0.5.5",
"html-webpack-plugin": "3.2.0",
"json-loader": "0.5.7",
"nodemon": "1.18.9",
"nodemon-webpack-plugin": "4.2.2",
"react": "16.12.0",
"react-dom": "16.12.0",
"react-router-dom": "5.1.2",
"sass-loader": "8.0.0",
"style-loader": "1.0.1",
"styled-components": "4.4.1",
"typeface-roboto": "0.0.75",
"webpack": "4.41.2",
"webpack-cli": "3.3.10",
"webpack-node-externals": "1.7.2"
}
}
my .babelrc"
{
"presets": [
"#babel/preset-env",
"#babel/react"
],
"plugins" : [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-runtime"
]
}

Get grunt-stylint to listen to all stylus files

I am trying to get my Gruntfile.js to lint all my stylus files using grunt-stylint, but I am having trouble getting it to listen to all my stylus files, particularly those in subdirectories.
Here is my styles structure:
- assets
- styles
bunch-of-files.styl
- components
even-more-files.styl
I've got it watching all stylus files with this:
watch: {
options: {
livereload: true,
},
pug: {
files: '**/*.pug',
tasks: ['puglint'],
options: {
livereload: true,
},
},
stylus: {
files: '**/*.styl',
tasks: ['stylint','stylus'],
},
scripts :{
files: 'assets/js/*.js',
tasks: ['concat'],
options: {
interrupt: false,
},
},
server: {
files: ['.rebooted'],
options: {
livereload: true
}
}
},
But, the stylint task only looks at the bunch-of-files with this, and not the components/ folder:
stylint: {
options: {
config: '.stylintrc'
},
src: ['**/*.styl']
},
Others I've tried with the same results:
stylint: {
options: {
config: '.stylintrc'
},
src: ['assets/styles/**/*.styl']
},
stylint: {
options: {
config: '.stylintrc'
},
src: ['**/**/*.styl']
},
The only thing that worked was this, but now it only looks in that components/ directory:
stylint: {
options: {
config: '.stylintrc'
},
src: ['assets/styles/*/*.styl']
},
And when I pair that with one of the earlier ones, it only reads the first file. For example this only will read those bunch-of-files.
stylint: {
options: {
config: '.stylintrc'
},
src: ['**/*.styl','assets/styles/*/*.styl']
},
Ideas?
**
editing w full gruntfile + package.json
Gruntfile:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
stylus: {
build: {
options: {
compress: false,
},
files: {
'public/css/main.css': 'assets/styles/main.styl',
}
}
},
concat: {
options: {
stripBanners: true,
},
basic: {
src: ['assets/js/*.js'],
dest: 'public/js/main.js',
},
},
jshint: {
all: ['Gruntfile.js', 'app.js', 'assets/**/*.js'],
options: {
force: true,
curly: true,
eqeqeq: true,
eqnull: true,
browser: true,
globals: {
jQuery: true
},
},
},
stylint: {
options: {
config: '.stylintrc'
},
src: ['**/*.styl']
},
puglint: {
src: '**/*.pug',
options: {
requireClassLiteralsBeforeAttributes: true,
requireIdLiteralsBeforeAttributes: true,
requireLowerCaseAttributes: true,
requireLowerCaseTags: true,
validateIndentation: 2,
disallowDuplicateAttributes: true,
validateAttributeQuoteMarks: "\""
}
},
watch: {
options: {
livereload: true,
},
pug: {
files: '**/*.pug',
tasks: ['puglint'],
options: {
livereload: true,
},
},
stylus: {
files: '**/*.styl',
tasks: ['stylint','stylus'],
},
scripts :{
files: 'assets/js/*.js',
tasks: ['concat'],
options: {
interrupt: false,
},
},
server: {
files: ['.rebooted'],
options: {
livereload: true
}
}
},
nodemon: {
dev: {
script: 'app.js',
options: {
nodeArgs: ['--debug'],
env: {
PORT: '3000'
},
// omit this property if you aren't serving HTML files and
// don't want to open a browser tab on start
callback: function (nodemon) {
nodemon.on('log', function (event) {
console.log(event.colour);
});
// refreshes browser when server reboots
nodemon.on('restart', function () {
// Delay before server listens on port
setTimeout(function() {
require('fs').writeFileSync('.rebooted', 'rebooted');
}, 1000);
});
}
}
}
},
concurrent: {
target: [['jshint', 'stylint', 'stylus', 'puglint', 'concat', 'watch'],'nodemon' ],
options: {
logConcurrentOutput: true
}
}
});
// Load plugins.
grunt.loadNpmTasks('grunt-contrib-stylus');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-stylint');
grunt.loadNpmTasks('grunt-puglint');
// Default task(s).
grunt.registerTask('default', ['concurrent']);
};
Package.json
{
"name": "",
"version": "",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"font-awesome-stylus": "^4.5.0",
"grunt": "^0.4.5",
"grunt-cli": "^1.1.0",
"grunt-concurrent": "^2.2.1",
"grunt-contrib-concat": "^1.0.0",
"grunt-contrib-jshint": "^1.0.0",
"grunt-contrib-stylus": "^1.2.0",
"grunt-contrib-watch": "^1.0.0",
"grunt-nodemon": "^0.4.1",
"grunt-puglint": "^1.0.0",
"grunt-stylint": "^0.1.2",
"mustache-express": "^1.2.2",
"open": "0.0.5",
"pug-lint-config-clock": "^1.1.1",
"reload": "^0.7.0",
"stylint": "^1.3.7"
},
"dependencies": {
"express": "^4.13.4",
"pug": "^2.0.0-beta2"
}
}