无法弄清楚如何解决 POST 请求问题。我正在尝试在站点上实现授权(通过 Vuejs、vuex、vue-router、axios)。如果你能给我一些建议,我会很高兴的。我搜索了论坛的信息,但其他地方描述的情况不适合我的情况。为什么是 404(确定)?如果正常,那为什么是404?这是否意味着服务器已经收到我的数据,但无法比较数据是否正确?
我有以下组件/页面:
应用程序.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home page</router-link> |
<router-link to="/login">Login</router-link>
<span v-if="isLoggedIn"> | <a @click="logout">Logout</a></span>
</div>
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
computed : {
isLoggedIn : function(){ return this.$store.getters.isLoggedIn}
},
methods: {
logout: function () {
this.$store.dispatch('logout')
.then(() => {
this.$router.push('/login')
})
}
},
created: function () {
this.http.interceptors.response.use(function (err) {
return new Promise(function (resolve) {
if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
this.$store.dispatch("logout")
resolve()
}
throw err;
});
});
},
}
</script>
LoginAnalytics.vue 在这里用户必须输入数据:手机和密码,用于授权
<template>
<div>
<form class="login" @submit.prevent="login">
<h1>Sign in</h1>
<label>Mobile</label>
<input required v-model="mobile" type="tel" placeholder="mobile phone"/>
<label>Password</label>
<input required v-model="password" type="password" placeholder="Password"/>
<hr/>
<button type="submit">Login</button>
</form>
</div>
</template>
<script>
export default {
data(){
return {
mobile : "",
password : ""
}
},
methods: {
login: function () {
let login = this.mobile
let password = this.password
this.$store.dispatch('login', { login, password })
.then(() => this.$router.push('/secure'))
.catch(err => console.log(err))
}
}
}
</script>
Vuex 商店。这里我创建了一个 axios post 请求来联系服务器。
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import { API_BASE_URL, TEMPORARY_TOKEN } from '../config';
Vue.use(Vuex);
export default new Vuex.Store({
state:{
trainings: [],
incomings: [],
sources: [],
avgShedule: [],
metro: [],
conversion: [],
avgIncome: [],
status: '',
token: localStorage.getItem('token') || '',
user : {},
},
mutations:{
auth_request(state){
state.status = 'loading'
},
auth_success(state, token, user){
state.status = 'success'
state.token = token
state.user = user
},
auth_error(state){
state.status = 'error'
},
logout(state){
state.status = ''
state.token = ''
},
},
getters:{
isLoggedIn: state => !!state.token,
authStatus: state => state.status,
},
actions:{
login({commit}, user){
return new Promise((resolve, reject) => {
commit('auth_request')
axios({
url: `${API_BASE_URL}/analytics.auth`,
data: user,
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
})
.then(resp => {
const token = resp.data.token
const user = resp.data.user
localStorage.setItem('token', token)
axios.defaults.headers.common['Authorization'] = token
commit('auth_success', token, user)
resolve(resp)
})
.catch(err => {
commit('auth_error')
localStorage.removeItem('token')
reject(err)
})
})
},
logout({commit}){
return new Promise((resolve) => {
commit('logout')
localStorage.removeItem('token')
delete axios.defaults.headers.common['Authorization']
resolve()
})
}
}
},
)
路由器。以下是在页面和组件之间切换的所有链接。
import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import Analytics from '@/pages/Analytics-test.vue'
import LoginAnalytics from '@/components/LoginAnalytics.vue'
import HomeAnalytics from '@/components/HomeAnalytics.vue'
Vue.use(Router)
let router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: HomeAnalytics
},
{
path: '/login',
name: 'login',
component: LoginAnalytics
},
{
path: '/secure',
name: 'secure',
component: Analytics,
meta: {
requiresAuth: true
}
},
]
})
router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.requiresAuth)) {
if (store.getters.isLoggedIn) {
next()
return
}
next('/login')
} else {
next()
}
})
export default router
另外:main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import store from './store'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$http = axios;
const token = localStorage.getItem('token')
if (token) {
Vue.prototype.$http.defaults.headers.common['Authorization'] = token
}
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app')
每次我输入正确的授权数据时,我都会在控制台中收到以下错误: