Why do I get this error only when my application is in production? - express

I am developing an application with NuxtJS and SSR, I am also using axios and auth modules. Everything works perfectly in localhost, but later when I upload the application to the host (Vercel) and try to log in, it gives me the 405 error. Does anyone know why this happens? The server is created with express
Error: Request failed with status code 405
at t.exports (237de42.js:2)
at t.exports (237de42.js:2)
at XMLHttpRequest._.onreadystatechange (237de42.js:2)
This is my nuxt.config.js file:
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
ssr: true,
// Global page headers: https://go.nuxtjs.dev/config-head,
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next',
'~/modules/api/index.js'
],
env:{
baseUrl: process.env.BASE_URL
},
axios: {
credentials: true,
https: true,
baseURL: 'https://www.encontrarhogar.com.ar/',
init(axios) {
axios.defaults.withCredentials = true
}
},
head: {
title: 'Encontrar Hogar',
htmlAttrs: {
lang: 'en'
},
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' },
{ rel: 'stylesheet', href: '/normalize.css' },
{ rel: 'stylesheet', href: "https://unpkg.com/swiper/swiper-bundle.min.css" }
],
script: [
{ src: "https://kit.fontawesome.com/57d52ad1ee.js", crossorigin: "anonymous" },
]
},
loading: {
color: 'black',
height: '8px',
continuous: true
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
'#/assets/css/index.css'
],
auth: {
strategies: {
local: {
token: {
property: 'token'
},
user: {
property: 'user'
},
endpoints: {
login: { url: '/server/api/usuarios/login', method: 'post', propertyName: 'data' },
user: { url: '/server/api/usuarios/mi-perfil', method: 'get', propertyName: 'data' },
logout: { url: '/server/api/usuarios/logout', method: 'delete' }
}
}
}
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: ['~/plugins/swiper.js'],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true
}

Related

why nuxt app is to slow in phon, vuetify ,how can I increment performance on phone

hi I have nuxt app it work good and fast in pc but in phone is to slow I use vuetify in my app And I'm suspicious of this :) (The reason for the slowness of app is vuetify)
It seems to involve RAM and CPU, and because the phone is weaker, it slows down drastically.
how can I increment performance on phone .
for example it load 1s in pc but in phone it load 4s
and if it load 5s in pc in phone load 14s
is is my nuxt.config
export default {
ssr: false,
loadingIndicator: '~/static/html/loading.html',
head: {
titleTemplate: '%s | ****',
title: '****',
htmlAttrs: {
lang: 'fa',
},
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' }],
},
css: [
'#/static/fonts/Ter/css/style.css',
'#/static/css/main.css',
'#/static/fonts/fontawesome/css/all.css',
],
plugins: [
{
src: '#/plugins/drag.js',
ssr: false,
},
{
src: '#/plugins/ft.js',
ssr: false,
},
{
src: '#/plugins/particles',
ssr: false,
},
{
src: '#/plugins/axios.js',
ssr: false,
},
{
src: '#/plugins/lang.js',
},
{
src: '#/plugins/vuetify.js',
},
{
src: '#/plugins/Analytics.js',
ssr: true,
},
{
src: '#/plugins/Carousel3d.js',
ssr: true,
},
{
src: '#/plugins/EventBus.js',
},
],
components: true,
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth',
'#nuxtjs/sitemap',
'#nuxtjs/robots',
'nuxt-i18n',
],
i18n: {
defaultLocale: 'fa',
lazy: true,
langDir: '~/langs',
locales: [
{ code: 'en', name: 'english', iso: 'en-US', file: 'en.js', dir: 'ltr' },
{ code: 'fa', name: 'پارسی', iso: 'fa-IR', file: 'fa.js', dir: 'rtl' },
{ code: 'ar', name: 'العربی', iso: 'ar-QA', file: 'ar.js', dir: 'rtl' },
],
},
robots: {
UserAgent: '*',
Disallow: '/dashboard',
},
sitemap: {
hostname: 'https://****/',
exclude: ['/forget-password'],
},
axios: {
// baseURL: 'https://****/api/',
// baseURL: 'https://****/api/',
baseURL: 'http://****/api/',
headers: {
common: {
customer: 'true',
},
},
},
env: {
baseURL: 'http://****/',
selfURL: 'https://****/',
cookieURL: 'localhost',
},
build: {
html: {
minify: {
collapseBooleanAttributes: true,
decodeEntities: true,
minifyCSS: true,
minifyJS: true,
processConditionalComments: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
trimCustomFragments: true,
useShortDoctype: true,
minifyURLs: true,
removeComments: true,
removeEmptyElements: true,
},
},
},
auth: {
strategies: {
local: {
endpoints: {
login: {
url: 'link/verification',
method: 'post',
propertyName: 'access_token',
},
user: false,
},
token: {
maxAge: 60 * 60,
},
autoFetchUser: false,
},
},
},
}
This kind of question cannot be answered easily with just that. Improving performance can take a lot of analysis, can come from various places and is a broad topic.
Here is two of my answers on this subject (still relevant in your case):
How to increase speed performance in Nuxt with SSR
How to improve the LCP score of my Nuxt site?
Few things we can note on your nuxt.config.js:
using ssr: false is basically fallback'ing to a pure SPA behavior, so the initial loading time may be quite slow (as always, it depends also on how you measure it)
loading global CSS (css key) can be a penalty too
all of the plugins you're loading are adding to the bundle-size (and hence, increase the loading time), maybe think to load some of them locally
ssr: false is legacy, please use mode: 'client'
also, checking for some smaller alternatives may be interesting too (are tho 37kB of JS worth it?)
Other than this, there is also your overall code, some middleware, some 3rd party like Google analytics, the list goes on and on.
But I think you have a decent starting point with this.

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!

Nuxt.js internal server error when navigating from direct link

enter code here
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'myApp',
htmlAttrs: {
lang: 'en'
},
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' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: ['~/assets/css/transition.css'],
pageTransition: "fade",
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{src:'~/plugins/axios'},
{ src: '~/plugins/vue-fbauth.js', ssr: false },
{ src: '~/plugins/vue-google', ssr: false },
{ src: "~/plugins/vue2-editor", ssr: false },
{ src: "~/plugins/slider", ssr: false },
{ src: "~/plugins/star-rating", ssr: false },
{ src: "~/plugins/mask", ssr: false },
{ src: "~/plugins/imageUpload", ssr: false },
{ src: "~/plugins/fileUpload", ssr: false },
{ src: "~/plugins/rangeSlider", 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: 'UA-198003695-1'
}]
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
'#nuxtjs/axios',
'#nuxtjs/auth-next', ['nuxt-lazy-load', {
defaultImage: '/spin2.gif'
}],
'nuxt-moment',
'#nuxt/http'
],
axios: {
baseURL: 'https://example.com/api/book.', // Used as fallback if no runtime config is provided
},
loading: {
color: '#F48245',
height: '4px'
},
target: 'server',
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
router: { middleware: ['checkUserAuth'] },
}
//htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^my-domain.com.br$
RewriteRule "(.*.(jpg|gif|png|svg|js|css|woff2))$" "http://127.0.0.1:3000/$1" [P,NC]
RewriteRule ^(.*) "http://127.0.0.1:3000/$2" [P,L]
I have some problems when I use nuxt.js with SSR, my web application works perfect in development mode, but in production mode, I have some unexpected errors, Errors occur when pages are linked directly, for SSR I am using Nuxt with asyncData and I get the following kind of error.
My application runs to domain https://www.example.com/ and Backend API is https://www.api.example.com/api/book. What is happening, where is the problem.
I have two questions
Could the reason be the difference between the domains?
How can I avoid page crashes on Internal server error if I am using nuxt Axios module?

Why can't I create routes with parameters in my serverMiddleware in nuxt?

I'm having a problem configuring the serverMIddleware property, everything works perfectly, but I can't create any other route than the initial route
Mi nuxt.config.js file:
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
ssr: true,
// Global page headers: https://go.nuxtjs.dev/config-head,
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next',
// '~/modules/api/index.js'
],
serverMiddleware:[
{ path: '/api', handler: '~/api/index.js'},
],
axios: {
baseURL: 'http://localhost:3000/',
},
head: {
title: 'Encontrar Hogar',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Encontra tu nuevo hogar en chacabuco. Todas las propiedades e inmuebles de Chacabuco en un mismo lugar' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: '/normalize.css' },
{ rel: 'stylesheet', href: "https://unpkg.com/swiper/swiper-bundle.min.css" }
],
script: [
{ src: "https://kit.fontawesome.com/57d52ad1ee.js", crossorigin: "anonymous" },
]
},
loading: {
color: 'black',
height: '8px',
continuous: true
},
css: [
'#/assets/css/index.css'
],
auth: {
cookie:{
options:{
secure: true
}
},
strategies: {
local: {
token: {
property: 'token'
},
user: {
property: 'user'
},
endpoints: {
login: { url: '/api/usuarios/login', method: 'post', propertyName: 'data' },
user: { url: '/api/usuarios/mi-perfil', method: 'get', propertyName: 'data' },
logout: false
}
}
}
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: ['~/plugins/swiper.js'],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true
}
/api/index.js file:
const bodyParser = require('body-parser')
const app = require('express')()
app.get('/api/:id?', (req, res) => res.send('hello'))
module.exports = app
If I try to create endpoints like the one that I will leave below, the only thing I get when making the get requests through the browser or postman is a 404 not found response, I do not understand what I am configuring wrong.
app.get('/api/products', (req, res) => res.send('products'))
Did you call http://localhost:3000/api/youridhere ?
According to your configuration and serveMiddleware, your link should be http://localhost:3000/api/api/youridhere
You have static target, change to "server" if you want serverMiddleware to work

Problem implementing nuxtjs/auth using local strategy

I'm following a nuxtjs tutorial and I'm having issues implementing nuxtjs/auth loginWith. It is pretty straightforward but I don't know why it doesn't work for me. tested with postman and the API responds with a token;
Everything looks okay, saves the token to cookies and local storage. Signup also works but it doesn't login. When I inspect with Vue dev tools, it shows login false and the user undefined when I'm expecting a user object. What could be wrong?
As it is, here's the method for Login.vue
async onLogin() {
try {
this.$auth.loginWith("local", {
data: {
email: this.email,
password: this.password
}
});
this.$router.push("/");
} catch (err) {
console.log(err);
}
}
here's also my nuxt.config.js
const URL = 'http://localhost:3000'
export default {
/*
** Nuxt rendering mode
** See https://nuxtjs.org/api/configuration-mode
*/
mode: 'universal',
/*
** Nuxt target
** See https://nuxtjs.org/api/configuration-target
*/
target: 'server',
/*
** Headers of the page
** See https://nuxtjs.org/api/configuration-head
*/
head: {
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: '/css/font-awesome/css/all.css' },
{ rel: 'stylesheet', href: '/css/default.css' }
]
},
/*
** Global CSS
*/
css: [],
/*
** Plugins to load before mounting the App
** https://nuxtjs.org/guide/plugins
*/
plugins: [],
/*
** Auto import components
** See https://nuxtjs.org/api/configuration-components
*/
components: true,
/*
** Nuxt.js dev-modules
*/
buildModules: [],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://bootstrap-vue.js.org
'bootstrap-vue/nuxt',
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
'#nuxtjs/pwa',
'#nuxtjs/auth',
// Doc: https://github.com/nuxt/content
// '#nuxt/content',
],
/*
**Axios Module config
** See https://axios.nuxtjs.org/options
*/
axios: {
proxy: true,
baseURL: URL
},
proxy: {
"/api": URL
},
/*
** Build configuration
** See https://nuxtjs.org/api/configuration-build/
*/
build: {
extend(config, ctx) {}
},
auth: {
strategies: {
local: {
endpoints: {
login: {
url: "/api/auth/login",
method: "post",
propertyName: "token"
},
user: {
url: "/api/auth/user",
method: "get",
propertyName: "token"
},
logout: true
}
}
}
}
};
Try this:
auth: {
strategies: {
local: {
endpoints: {
login: {
url: "/api/auth/login",
method: "post",
propertyName: "data.token"
},
user: {
url: "/api/auth/user",
method: "get",
propertyName: "data.user"
},
logout: true
}
}
}
}
As the response from the api is received inside data, when axios is used.
Okay Somehow, it only updates the after I refresh the entire browser. I thought the Hot reloading would suffice but it works. this is my auth strategies setup
auth: {
strategies: {
local: {
endpoints: {
login: {
url: "/api/auth/login",
method: "post",
propertyName: "data.token"
},
user: {
url: "/api/auth/user",
method: "get",
propertyName: "data.user"
},
logout: true
}
}
}
}
Thanks to all that commented. It has helped my confidence and problem solving ability.