So I've started to try nuxt and I'm at a point where I need axios but I can't use nuxt's axios module.
Here's the files
nuxt.config.js
module.exports = {
generate: {
routes: ['/']
},
head: {
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Flynd FMS' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
loading: { color: '#3B8070' },
modules: [
'#nuxtjs/router',
'#nuxtjs/dotenv'
],
plugins: [
{src: '#/plugins/axios.js', ssr: true},
{src: '#/plugins/vuex-router-sync.js', ssr: false}
],
build: {
vendor: ['axios'],
extend (config, ctx) {
if (ctx.dev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
plugins/axios.js
import axios from 'axios'
const instance = axios.create({
baseURL: process.env.API_HOST + ':' + process.env.API_PORT,
transformRequest: function (request) {
return request
}
})
export default instance
pages/Login.vue
<template>
</template>
<script>
</script>
In this state, the axios instance should have not been called even once, but strange thing that it produces an error page mentioning Request failed with status code 404
I suspected that it tried to hit axios's baseUrl, and I had it confirmed by checking nginx access log.
Is this an expected behavior? If not, can anyone point me how to avoid this?
Thanks!
Update
Okay, I got it working few minutes after posting this out by changing the ssr to false
nuxt.config.js
module.exports = {
plugins: [
{src: '#/plugins/axios.js', ssr: false}
]
}
But I'll keep this question open since that behavior in ssr mode still unexpected.
If you are using the latest version on nuxt.js it will which module to install.
Just Select the "Axios" by hitting space then you are good to go.
See Img here
Then you can make a global function for all your calls.
This is a global function for all get calls.
Don't forget to include this file in middleware folder.
getReq: async function (apiUrl, reqHeader) {
return await axios
.get(apiUrl, reqHeader)
.then((response) => {
console.log('Response from', apiUrl, ':', response)
return response
})
.catch((err) => {
if(err.response.data.error === 'session data missing'){
console.log("this:",this);
console.log("Error:",err.response.data.error);
// Popup Msg
Snackbar.open({
duration: 5000,
message: 'Session Error! Please Sign Again',
type: 'is-warning',
position: 'is-top-right',
actionText: 'Ok',
indefinite: false,
onAction: () => {
console.log("pap",location);
location.replace("/")
}
})
}
return err.response
})
},
This is how the global funtion is called.
const contractList = {
headers: {},
params: {
id: null,
state: this.state
},
withCredentials: true
}
const response = await ApiService.getReq(LIST_CONTRACT, contractList)
console.log('Response from getList', response)
The problem is with axios.
Handling of async request can cause this issue.
In my case, one of the external apis being used was down which was causing axios to fail.
Steps to debug and resolve this:
Identify where all is axios being used
Check if the apis are returning the correct response (check this outside of the project)
If required, comment apis and check which one if the api causing the issue
Additionally interceptors can be used to capture the error and show proper stack trace as done here
Related
I am new to nuxt.
I want to add following webpack config (from docs for ckeditor vue) to nuxt.js.config
https://ckeditor.com/docs/ckeditor5/latest/installation/getting-started/frameworks/vuejs-v2.html
const path = require( 'path' );
const CKEditorWebpackPlugin = require( '#ckeditor/ckeditor5-dev-webpack-plugin' );
const { styles } = require( '#ckeditor/ckeditor5-dev-utils' );
module.exports = {
// The source of CKEditor is encapsulated in ES6 modules. By default, the code
// from the node_modules directory is not transpiled, so you must explicitly tell
// the CLI tools to transpile JavaScript files in all ckeditor5-* modules.
transpileDependencies: [
/ckeditor5-[^/\\]+[/\\]src[/\\].+\.js$/,
],
configureWebpack: {
plugins: [
// CKEditor needs its own plugin to be built using webpack.
new CKEditorWebpackPlugin( {
// See https://ckeditor.com/docs/ckeditor5/latest/features/ui-language.html
language: 'en',
// Append translations to the file matching the `app` name.
translationsOutputFile: /app/
} )
]
},
// Vue CLI would normally use its own loader to load .svg and .css files, however:
// 1. The icons used by CKEditor must be loaded using raw-loader,
// 2. The CSS used by CKEditor must be transpiled using PostCSS to load properly.
chainWebpack: config => {
// (1.) To handle editor icons, get the default rule for *.svg files first:
const svgRule = config.module.rule( 'svg' );
// Then you can either:
//
// * clear all loaders for existing 'svg' rule:
//
// svgRule.uses.clear();
//
// * or exclude ckeditor directory from node_modules:
svgRule.exclude.add( path.join( __dirname, 'node_modules', '#ckeditor' ) );
// Add an entry for *.svg files belonging to CKEditor. You can either:
//
// * modify the existing 'svg' rule:
//
// svgRule.use( 'raw-loader' ).loader( 'raw-loader' );
//
// * or add a new one:
config.module
.rule( 'cke-svg' )
.test( /ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/ )
.use( 'raw-loader' )
.loader( 'raw-loader' );
// (2.) Transpile the .css files imported by the editor using PostCSS.
// Make sure only the CSS belonging to ckeditor5-* packages is processed this way.
config.module
.rule( 'cke-css' )
.test( /ckeditor5-[^/\\]+[/\\].+\.css$/ )
.use( 'postcss-loader' )
.loader( 'postcss-loader' )
.tap( () => {
return {
postcssOptions: styles.getPostCssConfig( {
themeImporter: {
themePath: require.resolve( '#ckeditor/ckeditor5-theme-lark' )
},
minify: true
} )
};
} );
}
};
My nuxt config is simply current, i did add some modules like axios,boostrap vue and auth to it.
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
// Target: https://go.nuxtjs.dev/config-target
target: "static",
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: "spa",
htmlAttrs: {
lang: "en",
},
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" }],
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: ["~/assets/less/colors.less"],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
"bootstrap-vue/nuxt",
"#nuxtjs/axios",
"#nuxtjs/auth-next",
],
auth: {
redirect: {
login: "/login",
logout: "/login",
callback: false,
home: "/",
},
strategies: {
laravelSanctum: {
provider: "laravel/sanctum",
url: "http://localhost",
user: {
property: false, // <--- Default "user"
autoFetch: true,
},
// endpoints: {
// login: { url: "api/login", method: "post" },
// logout: { url: "api/auth/logout", method: "post" },
// user: { url: "api/user", method: "get" },
// },
},
},
},
axios: {
credentials: true,
baseURL: "http://localhost", // Used as fallback if no runtime config is provided
// withCredentials: true,
headers: {
accept: "application/json",
common: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
"Access-Control-Allow-Credentials": true,
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {},
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
router: {
middleware: ["auth"],
},
};
And if config like that can be combine with webpack config for ckeditor , is that right way to do so ?
Or should i separate this and build in another direcrory with another sepparate webpack config?
I guess you're looking for that one: https://nuxtjs.org/docs/configuration-glossary/configuration-build#extend
Could create an external config and import it into this object or directly do that inline as most people do.
There are quite some answers on Stackoverflow anyway on how to achieve specific parts of the configuration, feel free to give it a search to find out what you need.
I attempted to add the Google Identity services script to nuxt.config.ts, which should expose window.google.
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
/* snip /*
head: {
script: [
{ src: "https://accounts.google.com/gsi/client" },
],
},
});
However, when I try to use it inside of a component, google is undefined.
<script setup lang="ts">
/* snip */
onMounted(() => {
// google is not defined
google.accounts.id.initialize({
client_id: "id.apps.googleusercontent.com",
callback: signInNew,
});
google.accounts.id.renderButton(document.getElementById("signIn")!, {
type: "standard",
});
google.accounts.id.prompt();
});
</script>
Upon further inspection, I found that the script is not added to the head at all. How can I fix this?
You may try the following way.
export default defineNuxtConfig({
app: {
head: {
script: [
{ src: "https://accounts.google.com/gsi/client" },
],
},
}
});
In my vue-app I'm using the #nuxtjs/proxy together with #nuxtjs/axios but for some reason I don't know, I always get an Request failed with status code 404 -error when calling the api.
Here is my nuxt.config.js
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
proxy: true,
},
proxy: {
"/api": {
target: "https://url-to-api.com/api",
pathRewrite: { "^/api/": "" },
}
},
then in my vue-component
created(){
const { data } = await this.$axios.get(
`/api/products/all`
)
...
}
when I check on the network tab, the request is:
https://mypage.com/api/products/all
that request returns like mentioned above Request failed with status code 404
What am I doing wrong?
nuxt version: 2.15.8
Try this:
// nuxt.config.js
axios: {
baseURL: '/',
browserBaseURL: '/',
proxy: true,
},
proxy: {
'/api/': {
target: process.env.BASE_URL,
pathRewrite: {'^/api/': ''},
},
},
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL,
},
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.BASE_URL,
},
},
and in your component:
created(){
const { data } = await this.$axios.get(
`products/all`
);
}
in .env:
BROWSER_BASE_URL=/api/
BASE_URL=https://url-to-api.com/api/
it works for me.
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’
}
}
I am creating a new project using nuxt.js v2.3.0. When I run npm run dev in my IDE console everything compiles correctly but when I go to the page I get the following error: Nuxt.js + Vue.js is detected on this page. Devtools inspection is not available because it's in production mode or explicitly disabled by the author.
Here is my nuxt.config.js file:
const pkg = require('./package');
module.exports = {
mode: 'spa',
dev: true,
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: pkg.description }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
bodyAttrs: {
class: 'h-100'
},
htmlAttrs: {
class: 'h-100'
}
},
/*
** Global CSS
*/
css: [
'#/assets/app.css'
],
/*
** Plugins to load before mounting the App
*/
plugins: [
'~/plugins/vue-notifications',
'~/plugins/vue2-sidebar'
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://github.com/nuxt-community/axios-module#usage
'#nuxtjs/axios',
// Doc: https://bootstrap-vue.js.org/docs/
'bootstrap-vue/nuxt',
// Doc: https://auth.nuxtjs.org/getting-starterd/setup
'#nuxtjs/auth',
'#nuxtjs/toast',
'#nuxtjs/font-awesome'
],
/*
** Axios module configuration
*/
axios: {
baseURL: 'http://users:8000'
},
/*
** Auth module configuration
*/
auth: {
strategies: {
password_grant: {
_scheme: 'local',
endpoints: {
login: {
url: '/oauth/token',
method: 'post',
propertyName: 'access_token'
},
logout: 'api/logout',
user: {
url: 'api/user',
method: 'get',
propertyName: false
},
},
tokenRequired: true,
tokenType: 'Bearer'
}
},
redirect: {
login: "/account/login",
logout: "/",
callback: "/account/login",
user: "/"
},
},
/*
** Toast configuration
*/
toast: {
position: 'top-right',
duration: 2000
},
loading: {
name: 'chasing-dots',
color: '#ff5638',
background: 'white',
height: '4px'
},
/*
** Router configuration
*/
router: {
middleware: ['auth']
},
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {
}
}
};
If I was running in production mode then I could understand but I'm not. I would expect vue-devtools to be running as normal.
I had to add the following to the nuxt.config.js:
vue: {
config: {
productionTip: false,
devtools: true
}
}
Now devtools shows up
tl:dr:
vue.config.devtools = true in my nuxt.config.js does not work for me.
I ran nuxt generate --devtools, then nuxt start and opened the website in my browser. Doing so I could use the Vue-Devtools.
After that I now can still use the Vue-Devtools, even when running nuxt dev and no vue.config.devtools flag set in my nuxt.config.js
Full story
So enabling the devtools flag in vue.config as in the accepted answer did not work for me either.
I first tried forcing the Vue-Devtools as described here. Adding a Plugin to set the window properties as described in the link. But without luck.
Digging in the Nuxt code I noticed the --devtools flag for the generate command and wanted to see if the Vue-Devtools work at all with Nuxt.
After running nuxt generate --devtools, then serving the application with nuxt start, I finally could access the devtools.
And now, even when running nuxt dev they are still accessible. And I don't have vue.config.devtools set at all in my nuxt.config.js. Weird. But maybe that helps someone.
More context: I am running Nuxt in spa mode, with target static as I don't have a Node server in the Backend and just want to build an SPA.
As #joshua jackson stated worked for me, while devtools: true did NOT.
Version:
Nuxt.js v2.10.0
Vue v2.6.10
vue: {
config: {
productionTip: false,
devtools: true
}
}
in nuxt.config.js
export default {
mode: 'universal',
devtools: true,
...
}
Hope this help someone stopped here.
I have struggled to get this working and tried all of the steps written here.
My issue was I had to run the server on a specified port.
server: {
port: process.env.PORT || 5000,
host: '0.0.0.0'
},
Adding this to nuxt.config.js solved the problem.