2
votes

Is it possible to pass data from Vuex Store to serverMiddleware in Nuxt.js?

  async SET_DATA({commit}, payload) {
    await this.$axios.$post('/api', { data: payload.data})
    commit('SET_DATA', payload.data)
  }

In nuxt.config

  serverMiddleware: [
    { path: '/api', handler: '~/api/index' }
  ]

Then how do I access the data in api/index.js ?

export default function (req, res, next) {
  // Get data from Store here

  next()
}
2

2 Answers

1
votes

Solution to my problem was found with bodyParser. Using app.use(bodyParser.json()).

0
votes

The only way I found is;

readFile & writeFile functions.

In nuxt.config

modules: ['~/api/api.js'],

In api/api.js

I use this method, because of servermiddleware causes bug when you try to build app.

module.exports = function (moduleOptions) {
//Add middleware only with `nuxt dev` or `nuxt start`
var fs = require('fs');

// Save file from env or vuex anything comes with this
fs.writeFile('envTransfer.txt',  JSON.stringify(this.options.env), function (err) {
  if (err) throw err;
  console.log('Saved!');
}); 

// Then call addServermiddleware  
 //Add middleware only with `nuxt dev` or `nuxt start`
if (this.options.dev || this.options._start) { 
  this.addServerMiddleware('~/api/index.js')
}
}

In the part api/index.js ( node & express )

const fs        = require('fs');
const express = require('express');
const app = express()
....
let content="";
fs.readFile('envTransfer.txt',  function(err, data) {
if (err) throw err;
content = data; 
var obj = JSON.parse(content);

 // do it what ever you want

app.get('/', (req, res, next) => {
     // res.send('API root')
})

// export the server middleware
    module.exports = {
      path: '/api',
      handler: app
   }
});