Search code examples
javascriptnode.jsvue.jsexpressvuex

How can I access Vuex Store from Node.js?


I have to access a state from server. I want to change the twitterName with a mutation after figure out from this. I set a getter but when I try to import store to js file it sends error. How can I import a state?

server/index.js

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const path = require('path')

const app = express()
app.use(bodyParser.json())
app.use(cors())

const tweets = require('./routes/api/tweets')
const twitterName = require('./routes/api/name')

app.use('/api/tweets', tweets)
app.use('/name/', twitterName)

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(__dirname + '/public/'))
  app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html'))
}

const port = process.env.PORT || 8081

app.listen(port, () => console.log(`Server started on port ${port}`))

server/name.js

const express = require('express')
const router = express.Router()

router.get('/:twitterName', (req, res) => {
  const name = req.params.twitterName
  res.status(200).send(name)
})

module.exports = router


store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    twitterName: 'name1234'
  },
  
  getters: {
    twitterName: (state) => state.twitterName
  }
  
  actions: {
    updateId({ commit }, id) {
      commit('setId', id)
    },
    async getTweetData({ state }) {
      const res = await axios.get('http://localhost:8081/name/' + state.twitterName)
      // do what you want with the data
    }
  },
})

Solution

  • You can’t use the store from the client in your express server from the simple reason that all the data used in client side of your application, including vuex store is saved in the browser, and you don’t have access to it in the server. This is not the correct way to achieve your goal.

    If you want to use data from the client you need to send it to your server, so you could use it there. So if you need the twitterName specifically you can do something like this:

    router.get('/tweets/:twitterName', (req, res) => {
      // const name = 'name123'
      const name = req.params.twitterName
      T.get(
        'search/tweets',
        { from: name, count: 5 },
        function (err, data, response) {
          if (err) {
            return res.status(400).json('Oops! Something went wrong.')
          }
          data.twitterName = '<new-name>'
          res.status(200).send(data)
        }
      )
    })
    
    

    And from the vuejs store:

    actions: {
       async getTweetData({ state, commit }) {
           const res = await axios.get('<your-server-ip>/' + state.twitterName)
           commit('setTwitterName', res.data.twitterName)
       } 
    },
    mutations: {
       setTwitterName(state, newTwitterName) {
           state.twitterName = newTwitterName
       }
    }