使用Vue、ElementUI实现登录注册,配置axios全局设置,解决CORS跨域问题
    		       		warning:
    		            这篇文章距离上次修改已过434天,其中的内容可能已经有所变动。
    		        
        		                
                
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
 
Vue.use(ElementUI)
 
// 设置axios全局配置
axios.defaults.baseURL = 'https://api.example.com' // 替换为你的API地址
axios.defaults.withCredentials = true // 允许跨域请求时携带凭证
 
// 解决CORS跨域问题
axios.interceptors.response.use(response => {
  return response
}, error => {
  if (error.response && error.response.status === 401) {
    // 处理未授权,例如跳转到登录页面
    console.log('未授权,可以在这里跳转到登录页面')
  }
  return Promise.reject(error)
})
 
// 登录方法示例
function login(credentials) {
  return axios.post('/login', credentials)
    .then(response => {
      // 登录成功后的处理逻辑
      console.log('登录成功', response)
    })
    .catch(error => {
      // 登录失败的处理逻辑
      console.error('登录失败', error)
    })
}
 
// 注册方法示例
function register(userInfo) {
  return axios.post('/register', userInfo)
    .then(response => {
      // 注册成功后的处理逻辑
      console.log('注册成功', response)
    })
    .catch(error => {
      // 注册失败的处理逻辑
      console.error('注册失败', error)
    })
}
 
// 在Vue组件中使用
export default {
  methods: {
    handleLogin() {
      login({ username: 'user', password: 'pass' }).then(() => {
        // 登录成功后的导航或其他操作
        this.$router.push('/home')
      })
    },
    handleRegister() {
      register({ email: 'user@example.com', password: 'pass' }).then(() => {
        // 注册成功后的导航或其他操作
        this.$router.push('/home')
      })
    }
  }
}在这个代码实例中,我们设置了axios的全局配置,包括基础URL和允许跨域请求携带凭证。我们还通过拦截器处理了CORS相关的错误,例如未授权的情况。然后,我们定义了login和register方法,这些方法使用axios发送POST请求到服务器。最后,我们展示了如何在Vue组件中使用这些方法来处理登录和注册逻辑。
评论已关闭