Reputation: 333
I'm trying to set the API base URL in Nuxt.js. I've used DreaMinder's answer from this question.
I get no errors but when I try to hit any endpoints from my app I get a 404 error (the endpoints to exist). The only way I can get my code to work is to put the full URL in each axios request.
This is my nuxt.config.js
import pkg from './package'
require('dotenv').config()
let development = process.env.NODE_ENV !== 'production'
export default {
mode: 'universal',
/*
** Headers of the page
*/
head: {
// title: pkg.name,
title: "AppName",
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' }]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: [],
/*
** Plugins to load before mounting the App
*/
plugins: [
'~/plugins/vue-cookies',
'~/plugins/vee-validate',
'~/plugins/moment',
'~/plugins/vue-truncate-filter',
'~/plugins/numeral'
],
/*
** Axios module configuration
*/
axios: {
// See https://github.com/nuxt-community/axios-module#options
// baseURL: process.env.API_BASE_URL || 'http://localhost:5000/v1'
baseURL: development ? 'http://localhost:5000/v1' : 'https://api.appname.com/v1'
},
/*
** Nuxt.js modules
*/
modules: [
'@nuxtjs/dotenv',
// Doc: https://axios.nuxtjs.org/usage
'@nuxtjs/axios',
// Doc: https://buefy.github.io/#/documentation
'nuxt-buefy'
],
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
Anyone know what I'm doing wrong?
Upvotes: 2
Views: 5479
Reputation:
I had same errors. But I fixed it to use proxy. Please try it. Here is my nuxt.config.js.
... ... ...
modules: [
... ... ...
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
axios: {
// See https://github.com/nuxt-community/axios-module#options
// baseURL: process.env.API_URL || 'http://localhost:3000/',
proxy:true,
},
proxy:{
'/api/': { target: [your base url], pathRewrite: {'^/api/': ''}, changeOrigin: true }
},
... ... ...
And You can call the endpoint using this.
let data= await this.$axios.get(
'/api/[your endpoint url],
{
params: {
... ... ...
},
headers: {
... ... ...
},
}
);
You need to install @nuxtjs/proxy npm module. Please try use this.
Upvotes: 1