I am converting my Nuxt application to SSR – because I want to use nuxtServerInit and asyncData. These are the steps I have taken to convert it.
- Remove
ssr: falsefromnuxt.config.js - Dispatch actions to initialize store’s state in
nuxtServerInitinsidestore/index.js
Now my nuxt.config.js looks like this
require("dotenv").config({ path: `.env.${process.env.NODE_ENV}` });
export default {
router: {
base: "/app/",
},
target: "static",
head: {
// Some head, meta, link config
},
css: ["@/assets/scss/main.scss"],
styleResources: {
scss: ["@/assets/scss/*.scss", "@/assets/scss/main.scss"],
},
plugins: ["@/plugins/apiFactory.js"],
components: true,
buildModules: [
"@nuxtjs/eslint-module",
["@nuxtjs/dotenv", { filename: `.env.${process.env.NODE_ENV}` }],
],
modules: [
"bootstrap-vue/nuxt",
"@nuxtjs/style-resources",
["nuxt-sass-resources-loader", "@/assets/scss/main.scss"],
],
build: {
splitChunks: {
layouts: true,
},
},
};
And the store/index.js looks like this.
import axios from "axios";
export const state = () => ({
data: [],
});
export const mutations = {
setData(state, data) {
state.data = data;
},
};
export const actions = {
async nuxtServerInit({ dispatch }) {
// Before converting to SSR this action was dispatched in page/component that need this data
await dispatch("fetchData");
},
async fetchData({ commit }) {
const { data } = await axios.get("http://localhost:3030/my/api/path");
commit("setData", data);
},
};
export const getters = { /* some getters */ };
But after I restarted the development server – I was greeted with connect ECONNREFUSED 127.0.0.1:3030
These are the steps I’ve taken after that
- Check if the API on
localhost:3030is running and accessible – It’s running and accessible via direct URL and Postman - Comment out the
// await dispatch("fetchData");innuxtServerInit– restarted the dev server – site is accessible again but without initial data.
So, I suspected that the action dispatched in nuxtServerInit cause the problem – If it is how do I fix this problem or where should I look into next? Please let me know, Thanks!
Additional Information
- The API on
localhost:3030is Lumen version 7.2.2 - The application will be deployed on shared hosting
Advertisement
Answer
The main reason is that nuxt can’t connect to your host from where it resides. In my case it is docker container where 127.0.0.1 is… the container! So you have to change baseUrl to actually accessible server from that container.
const axiosPlugin: Plugin = ({ $axios, isDev }) => {
if (isDev && process.server) $axios.setBaseURL('http://172.22.0.1:3000/api')
}
