How to resolve Apollo error 401 accessing DatoCMS - vuejs2

I followed this guide:
https://medium.com/#marcmintel/quickly-develop-static-websites-with-vuejs-a-headless-cms-and-graphql-bf64e75910d6
but when I run npm run dev I get error 401 on my localhost:3000
this is my nuxt.config.js
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'hello-world',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
modules: [
'#nuxtjs/apollo',
],
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.datocms.com',
getAuth: () => 'Bearer XXXXXXXXXXXXX' //my apikey
}
}
}
}
And this is the vue file performing the query. I'm currently displaying nothing in the page but I still get the error.
<template>
<div>
All blog posts
</div>
</template>
<script>
import gql from 'graphql-tag'
export default {
apollo: {
allPosts: gql`{
allPosts{
title,
text,
slug
}
}`
}
}
</script>
The post data type is correctly defined in DatoCMS, I tested it with the API Explorer

Found the solution in the comments of the article.
You need to put your auth in a separate file like this and format it as follows:
~/apollo/config.js
export default function(context){
return {
httpEndpoint: ‘https://graphql.datocms.com',
getAuth:() => ‘my-token’ //Bearer is added by default
}
}
Then in nuxt.config.js
apollo:
apollo: {
clientConfigs: {
default: ‘~/apollo/config.js’
}
}

Related

Nuxt 3: nuxt-socket-io throwing Cannot add property registeredWatchers

I'm trying to setup nuxt-socket-io on a Nuxt 3 project. I followed all the setup steps in the nuxt-socket-io documentation but it's throwing the following Error:
Cannot add property registeredWatchers, object is not extensible.
Does anyone know what it means? What I'm missing?
Here's what my code looks like:
nuxt.config.js:
export default defineNuxtConfig({
modules: [
'#nuxtjs/tailwindcss',
'nuxt-socket-io',
],
app: {
head: {
title: 'Nuxt Dojo',
meta: [
{ name: 'description', content: 'Everything about Nuxt 3'},
],
link: [
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons'}
]
}
},
runtimeConfig: {
public: {
apiUrl: process.env.API_URL,
},
},
io: {
// module options
sockets: [{
name: 'main',
url: 'http://localhost:4000'
}]
},
})
pages/index.vue:
<template>
<div>
<h2 class="text-xl">Index</h2>
<p>This project should become a messaging app.</p>
</div>
</template>
<script setup>
const socket = useNuxtApp().$nuxtSocket({
name: 'main',
channel: '/',
emitTimeout: 1000,
});
/* Listen for events: */
socket.on('message', (msg, cb) => {
console.log({ msg, cb });
});
</script>

how to override the vuetify scss varibales in nuxt3 + vite

I want to override the vuetify scss variable to change the v-text-field border-radius
I tried to set up the vueitfy3 with vite-plugin-vuetify and some addition config to overriding the variables, but faced so many warnings related to vuetify:
Code sample
/* nuxt.config */
import vuetify from 'vite-plugin-vuetify'
export default defineNuxtConfig({
build: {
transpile: ['vuetify'],
},
modules: [ /* updated */
async (options, nuxt) => {
nuxt.hooks.hook('vite:extendConfig', (config) =>
config.plugins.push(
vuetify({
styles: {
configFile: 'assets/variables.scss',
},
})
)
);
}
],
vite: {
define: {
'process.env.DEBUG': false,
},
css: {
preprocessorOptions: {
scss: {
additionalData: `
#import "assets/variables.scss";
`
}
}
}
},
app: {
head: {
title: '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
}
}
})
// plugins/vuetify.ts
import { createVuetify } from 'vuetify'
import * as components from 'vuetify/components'
import * as directives from 'vuetify/directives'
import 'vuetify/styles'
export default defineNuxtPlugin(nuxtApp => {
const vuetify = createVuetify({
components,
directives
})
nuxtApp.vueApp.use(vuetify)
})
/* assets/variables.scss */
#use 'vuetify/settings' with ( /* updated */
$application-background: red,
$application-color: red
);
All defined varibales in the 'varibales.scss' are detected, but i want to override the vuetify varibales.
I tried to set up the vueitfy3 with vite-plugin-vuetify and some addition config to overriding the variables, but faced with so many warnings related to vuetify.
warrnings
nuxt.config
import vuetify from 'vite-plugin-vuetify'
export default defineNuxtConfig({
build: {
transpile: ['vuetify'],
},
modules: [
async (options, nuxt) => {
nuxt.hooks.hook('vite:extendConfig', (config) =>
// eslint-disable-next-line #typescript-eslint/ban-ts-comment
// #ts-ignore
config.plugins.push(
vuetify({
styles: {
configFile: 'assets/variables.scss',
},
})
)
);
}
],
vite: {
define: {
'process.env.DEBUG': false,
},
css: {
preprocessorOptions: {
scss: {
additionalData: `
#import "assets/variables.scss";
`
}
}
}
},
app: {
head: {
title: '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
}
}
})
plugins/vuetify
import { createVuetify } from 'vuetify'
import * as components from 'vuetify/components'
import * as directives from 'vuetify/directives'
import 'vuetify/styles'
export default defineNuxtPlugin(nuxtApp => {
const vuetify = createVuetify({
components,
directives
})
nuxtApp.vueApp.use(vuetify)
})
assets/variables.scss
#use 'vuetify/settings' with (
$application-background: red,
$application-color: red
);

Nuxt.js Oauth sometimes crashes whole webpage

I have created Nuxt.js application, I decided to build in Nuxt/auth module, everything works fine in web browsers, but somethimes when user navigates with mobile browser my application is crushed, simply it don't respond nothing, also there is no api calls, but after one refresh everything works fine, I can not guess what's happening, I could not find anything in the resources available on the Internet.
const axios = require('axios')
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'app',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
// { src: "//code-eu1.jivosite.com/widget/UoBOrMfSmm", async: true },
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [ '~/assets/css/transition.css', '~/assets/css/errors.css' ],
pageTransition: "fade",
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{ src: "~/plugins/star-rating", ssr: false },
{ src: "~/plugins/mask", ssr: false },
{ src: "~/plugins/rangeSlider", ssr: false },
{ src: "~/plugins/vueSelect", ssr: false },
{ src: "~/plugins/vuelidate", ssr: false },
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
[ '#nuxtjs/google-analytics', {
id: 'xxx'
} ]
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
'#nuxtjs/axios',
'#nuxtjs/toast',
'#nuxtjs/auth-next',
[ 'nuxt-lazy-load', {
defaultImage: '/spin2.gif'
} ],
[ 'nuxt-facebook-pixel-module', {
/* module options */
track: 'PageView',
pixelId: '',
autoPageView: true,
disabled: false
} ],
'nuxt-moment',
'#nuxtjs/robots',
'#nuxtjs/sitemap'
],
moment: {
locales: ['ru', 'en']
},
toast: {
position: 'top-center',
},
robots: [
{
UserAgent: '*',
Disallow: ['/user', '/admin'],
},
],
axios: {
baseURL: 'https://api.test.com/', // Used as fallback if no runtime config is provided
},
sitemap:{
exclude:[
'/user',
'/admin',
'/admin/*',
'/user/*',
],
defaults: {
changefreq: 'daily',
priority: 1,
lastmod: new Date()
},
routes: async () => {
const { data } = await axios.get('https://api.test.com/api/cars/all')
return data.map((product) => `https://test.com/product/${product.id}/${product.name}`)
}
},
loading: {
color: '#F48245',
height: '4px'
},
target: 'server',
/* auth */
auth: {
plugins:[
{ src: "~/plugins/providers", ssr:false},
],
redirect: {
login: '/',
logout: '/',
home: '/',
callback: '/callback'
},
strategies: {
local: {
token: {
property: 'user.token',
},
user: {
property: false
},
endpoints: {
login: { url: 'api/login', method: 'post' },
logout: { url: 'api/logout', method: 'post' },
user: { url: 'api/user', method: 'get' }
},
},
facebook: {
endpoints: {
userInfo: 'https://graph.facebook.com/v6.0/me?fields=id,name,picture{url}',
},
redirectUri:'xxx',
clientId: '184551510189971',
scope: ['public_profile', 'email'],
},
google: {
responseType: 'token id_token',
codeChallengeMethod: '',
clientId: 'xxx',
redirectUri: 'https://test.com/callback',
scope: ['email'],
},
},
cookie: {
prefix: 'auth.',
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
};
This is my plugins directory file, where i am handling client oauth process.
export default async function ({ app }) {
console.log('auth executed')
if (!app.$auth.loggedIn) {
return
} else {
console.log('auth executed inside loop')
const auth = app.$auth;
const authStrategy = auth.strategy.name;
if (authStrategy === 'facebook') {
let data2 = {
fb_token: auth.user.id,
first_name: auth.user.name
}
try {
const response = await app.$axios.$post("/api/oauth", data2);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
} else if (authStrategy === 'google') {
let dataGoogle = {
google_token: auth.user.sub,
first_name: auth.user.given_name,
last_name:auth.user.family_name
}
try {
const response = await app.$axios.$post("/api/oauth", dataGoogle);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
}
}
}
For any issues related to DOM hydration, you can check my answer here: https://stackoverflow.com/a/67978474/8816585
It does have several possible cases (dynamic content with a difference between client side and server side rendered template, some random functions, purely wrong HTML structure etc...) and also a good blog article from Alex!

error "window is not defined " when using plugin Vue.js

Just learning vue. Install the slider plugin for the site from here: https://github.com/surmon-china/vue-awesome-swiper . Transferred the code and received such an error: 'window is not defined' Code below. I use nuxt.js. There are several solutions on the Internet, but none of them helped me.
slider.vue
<script>
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper';
if (process.browser) {
const VueAwesomeSwiper = require('vue-awesome-swiper/dist/ssr')
Vue.use(VueAwesomeSwiper)
}
export default {
components: {
swiper,
swiperSlide
},
data() {
return {
swiperOption: {
slidesPerView: 'auto',
centeredSlides: true,
spaceBetween: 30,
pagination: {
el: '.swiper-pagination',
clickable: true
}
}
}
}
}
</script>
vue-awesome-swiper.js
import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'
// require styles
import 'swiper/dist/css/swiper.css'
Vue.use(VueAwesomeSwiper,{});
nuxt.config.js
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'stud-cit',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Stud-cit site' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
loading: { color: 'blue'},
plugins: [
'~/plugins/vuetify',
'~/plugins/vue-awesome-swiper' ,
'~/plugins/vuePose'
],
build: {
vendor :['vue-awesome-swiper/dist/ssr'],
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
});
}
}
}
};
This library has special build for SSR.
Reference
import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper/dist/ssr'
Vue.use(VueAwesomeSwiper)

Angular2 - Nebular theme API endpoints

I am developing application under Angular2 and I choose Nebular frontend - https://akveo.github.io/nebular/#/home
Documentation is not really detailed for me and I am not expert in Angular2.
I am struggling in part - API endpoints https://akveo.github.io/nebular/#/docs/auth/configuring-a-provider
Where I can save the API basepoint? In which file or part of file?
Affected code:
{
baseEndpoint: 'http://...
...
My code (core.module.js):
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '#angular/core';
import { CommonModule } from '#angular/common';
import { NbEmailPassAuthProvider, NbAuthModule } from '#nebular/auth';
import { throwIfAlreadyLoaded } from './module-import-guard';
import { DataModule } from './data/data.module';
import { AnalyticsService } from './utils/analytics.service';
import { environment } from './../../environments/environment';
const NB_CORE_PROVIDERS = [
...DataModule.forRoot().providers,
...NbAuthModule.forRoot({
providers: {
email: {
service: NbEmailPassAuthProvider,
config: {
delay: 3000,
login: {
rememberMe: true,
},
},
},
},
forms: {
validation: {
password: {
required: true,
minLength: 6,
maxLength: 255,
},
email: {
required: true,
}
}
}
}).providers,
AnalyticsService
];
#NgModule({
imports: [
CommonModule,
],
exports: [
NbAuthModule,
],
declarations: [],
})
export class CoreModule {
constructor(#Optional() #SkipSelf() parentModule: CoreModule) {
throwIfAlreadyLoaded(parentModule, 'CoreModule');
}
static forRoot(): ModuleWithProviders {
return <ModuleWithProviders>{
ngModule: CoreModule,
providers: [
...NB_CORE_PROVIDERS,
],
};
}
}
I'm trying to put it to work and i'm at the same part of the manual.
As i could understand, the baseEndpoint: 'http://... thing and others configuration goes on the authentication provider config variable. Looks like it's of the type NgEmailPassAuthProviderConfig (defined on #nebular/auth/providers/email-pass-auth.options).
#NgModule({
imports: [
// ...
NbAuthModule.forRoot({
providers: {
email: {
service: NbEmailPassAuthProvider,
config: {
baseEndpoint: 'http://localhost:8080', // <-- here
login: {
rememberMe: true,
},
},
},
},
}),
],
});
I already managed to put it to call a api method on a Spring rest API. I can see the HttpResponse on browser with status: 200 but still getting "Oh snap!
Something went wrong." message on the NbLoginComponent.
In order to create the api correctly follow these steps
1) implement this on your localhost :
2) add this code to core.module.ts
strategies: [
NbPasswordAuthStrategy.setup({
name: 'email',
login: {
requireValidToken: false,
},
baseEndpoint: 'http://localhost:4400/api/auth/',
logout: {
redirect: {
success: '/auth/login',
failure: '/auth/login',
},
},
requestPass: {
redirect: {
success: '/auth/reset-password',
},
},
resetPass: {
redirect: {
success: '/auth/login',
},
},
errors: {
key: 'data.errors',
},
}),
],
I propose to create a proxy proxy.conf.json in the root of the project with content
{
   "/api/*": {
     "target": "http://localhost",
     "secure": false,
     "logLevel": "debug"
   }
}
then start the angular application with the command
$ ng serve --port 8097 --proxy-config proxy.conf.json
remember the * 8097 * port you mentioned in the ng serve command
to finish adding your base url as follows:
{
baseEndpoint: '/api/',
...
for more information about proxy config refer you to https://morioh.com/p/07bddb33e3ab
I hope this help