自学路上遇到的头痛的问题,写下来自己做个备忘,也希望帮助到初学者的你们。比心~
1、修改api->user.js文件:
export function login(data) {
return request({
url: 'api/merchant_user/login/login', // url对应改成正确的api地址
method: 'post',
data
})
}
// 这个文件还有两个函数,都对应改一下url即可
2、修改utils->request.js
搜索config.headers将token的命名格式改成服务器返回的token命名格式
config.headers['XX-Token'] = getToken() // 此次记录时用返回的格式是XX-Token
修改service.interceptors.response.use
if (res.code !== 20000){...}
// 改为:
if (res.code !== 20000 && res.code !== 1) // 因为我服务器成功返回的是 1 ,所以加了一个值1
同时我还修改了baseURL 的值,有的同学不修改也能成功,根据自己实际情况
baseURL: 'https://ceshi.xxxxxxxx.com', // url = base url + request url
3、设置代理跨域 vue.config.js
// 设置devServer的值
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
// before: require('./mock/mock-server.js') // 注释掉这一行
proxy: {
'/dev-api': { // 因为默认开发api就是dev-api,所以我这里就没有改其他名字也叫dev-api
target: 'https://ceshi.xxxxxxxx.com/',
pathRewrite: { '^/dev-api': '' }, // 记得也哟改dev-api
}
}
}
修改完配置文件以后记得重启服务
修改utils->request.js
// create an axios instance
const service = axios.create({
baseURL: 'https://ceshi.xxxxxxxx.com/', // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 5000, // request timeout
headers: {
'XX-Token': getToken(),
'XX-Device-Type':'web' // 后端如果需要特别的请求头,就进行设置,如果没有特殊要求,不设置就可以,保持默认的值
}
})
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
baseURL: 'https://ceshi.xxxxxxxx.com/', // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 5000, // request timeout
headers: {
'XX-Token': getToken(),
'XX-Device-Type':'web'
}
})
// 请求拦截器
service.interceptors.request.use(
config => {
// do something before request is sent
if (store.getters.token) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
// XX-Device-Type
// XX-Token
config.headers['XX-Token'] = getToken()
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
const res = response.data
// if the custom code is not 20000, it is judged as an error.
if (res.code !== 20000 && res.code !== 1) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
// 相应成功做什么
return res
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const getDefaultState = () => {
return {
token: getToken(),
name: '',
avatar: ''
}
}
const state = getDefaultState()
const mutations = {
RESET_STATE: (state) => {
Object.assign(state, getDefaultState())
},
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
}
}
const actions = {
// user login
async login({ commit }, userInfo) {
const { username, password } = userInfo
let res = await login({ username: username.trim(), password: password })
console.log(res)
if(res.code == 1 ){
commit('SET_TOKEN', res.data.token)
console.log(res.data.token)
setToken(res.data.token)
}else{
return Promise.reject(new error('fail'))
}
// console.log(res)
// return new Promise((resolve, reject) => {
// .then(response => {
// const { data } = response
// commit('SET_TOKEN', data.token)
// setToken(data.token)
// resolve()
// }).catch(error => {
// reject(error)
// })
// })
},
// get user info
async getInfo({ commit, state }) {
let res = await getInfo(state.token)
if (!res.data) {
return reject('登录失效,请重新登陆')
}else{
const { name, avatar } = res.data.user
console.log(res.data)
commit('SET_NAME', name)
commit('SET_AVATAR', avatar)
}
// return new Promise((resolve, reject) => {
// getInfo(state.token).then(response => {
// const { data } = response
// if (!data) {
// return reject('Verification failed, please Login again.')
// }
// const { name, avatar } = data
// commit('SET_NAME', name)
// commit('SET_AVATAR', avatar)
// resolve(data)
// }).catch(error => {
// reject(error)
// })
// })
},
// user logout
logout({ commit, state }) {
removeToken() // must remove token first
resetRouter()
commit('RESET_STATE')
return '已经退出登录状态'
// return new Promise((resolve, reject) => {
// logout(state.token).then(() => {
// removeToken() // must remove token first
// resetRouter()
// commit('RESET_STATE')
// resolve()
// }).catch(error => {
// reject(error)
// })
// })
},
// remove token
resetToken({ commit }) {
return new Promise(resolve => {
removeToken() // must remove token first
commit('RESET_STATE')
resolve()
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
以上就是全部内容了,后面如果发现遗漏的地方再补充。