如何从Node.js访问Vuex Store



我必须从服务器访问一个状态。我想在弄清楚之后,用一个突变来改变twitterName。我设置了一个getter,但当我试图将存储导入到js文件时,它会发送错误。如何导入状态?

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
}
},
})

您不能在express服务器中从客户端使用存储,原因很简单,因为应用程序客户端使用的所有数据,包括vuex存储,都保存在浏览器中,并且您无法在服务器中访问它。这不是实现目标的正确方式。

如果你想使用来自客户端的数据,你需要将其发送到服务器,这样你就可以在那里使用它。因此,如果你特别需要twitterName,你可以这样做:

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)
}
)
})

从vuejs商店:

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
}
}

最新更新