Authentication NuxtJs-无法读取未定义的属性“headers”
我是NuxtJs的新手。我试图用axios实现一个外部API调用,我获取令牌并将其存储在cookie上。在开发过程中,一切都很顺利。但当我尝试运行npm run generate时,它会给我错误,我不知道该怎么办 当我删除nuxtSeverInit时,npm运行生成平稳运行。经过一些研究,我认为我正在使用的nuxtServerInit不应该被使用。谁能告诉我怎么做 这是新公司的第一个项目,所以我想证明自己。请帮帮我。你愿意吗 这是store/index.js文件Authentication NuxtJs-无法读取未定义的属性“headers”,authentication,cookies,vue.js,server-side-rendering,Authentication,Cookies,Vue.js,Server Side Rendering,我是NuxtJs的新手。我试图用axios实现一个外部API调用,我获取令牌并将其存储在cookie上。在开发过程中,一切都很顺利。但当我尝试运行npm run generate时,它会给我错误,我不知道该怎么办 当我删除nuxtSeverInit时,npm运行生成平稳运行。经过一些研究,我认为我正在使用的nuxtServerInit不应该被使用。谁能告诉我怎么做 这是新公司的第一个项目,所以我想证明自己。请帮帮我。你愿意吗 这是store/index.js文件 import Vuex fr
import Vuex from 'vuex'
var cookieparser = require('cookieparser')
const createStore = () => {
return new Vuex.Store({
state: {
auth: null,
},
mutations: {
update (state, data) {
state.auth = data
}
},
actions: {
nuxtServerInit ({ commit }, { req }) {
let accessToken = null
if (req.headers.cookie) {
var parsed = cookieparser.parse(req.headers.cookie)
if(parsed){
accessToken = parsed.auth
}
}
commit('update', accessToken)
},
}
})
}
export default createStore
中间件/authenticated.js文件
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.auth) {
return redirect('/login')
}
}
中间件/notAuthenticated.js文件
export default function ({ store, redirect }) {
// If the user is authenticated redirect to home page
if (store.state.auth) {
return redirect('/app/dashboard')
}
}
login.vue文件
validateBeforeSubmit() {
this.$validator.validateAll().then((result) => {
if (result) {
this.button_title = 'One moment ...';
let submitted_user_data = {
'username': this.emailAddress,
'client_id': this.user_uuid,
'password': this.password,
}
MerchantServices.do_user_login(submitted_user_data)
.then(response => {
let access_token = response.data.access_token;
this.postLogin(access_token);
})
.catch(error => {
this.$refs.invalid_credentials.open();
this.button_title = 'Sign in'
});
return;
}
});
},
postLogin: function(access_token_val) {
if(access_token_val != ''){
setTimeout(() => {
const auth = {
accessToken: access_token_val
}
this.$store.commit('update', auth)
Cookie.set('auth', auth)
this.$refs.invalid_credentials.open();
this.button_title = 'Sign in'
this.$router.push('/app/dashboard')
}, 1000)
}else{
alert('hello')
}
},
以及最后一个用户登录api调用,该调用还返回令牌
do_user_login(user){
var user_details = 'username='+user.username+'&client_id='+ user.client_id +'&grant_type=password&password='+user.password+''
return axios.post('myapiurl', user_details )
.then(response => {
return response;
});
},
根据req在nuxt generate上不可用。
您应该使用nuxt build,然后再使用nuxt start。显示req不能通过nuxt generate使用,这解释了为什么它没有定义。