You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Cli项目对接远程PHP API实现Admin路由登录拦截方案咨询

Solution for Vue Admin <-> PHP API Integration & Route Auth Guard

Hi there! I’ve worked on similar Vue + PHP projects before, so let’s break down your two core requirements and solve them step by step.


1. Connecting Vue Admin to PHP API (Dev & Production Environments)

Development Environment (Fix CORS Issues)

Since your Vue dev server runs on http://localhost:3001 and PHP API on http://localhost:3000, you’ll hit cross-origin request blocks. The simplest fix is using Vue CLI’s built-in proxy:

  1. Create/modify vue.config.js in your Admin Vue project root:
module.exports = {
  devServer: {
    proxy: {
      '/api': { // Match all requests starting with /api
        target: 'http://localhost:3000', // Your PHP API base URL
        changeOrigin: true, // Fixes CORS origin mismatch
        pathRewrite: {
          '^/api': '' // Optional: Remove /api prefix if your PHP API doesn’t use it
        }
      }
    }
  }
}
  1. In your Vue code (e.g., axios requests), use /api as the base path:
// Example: Fetch admin dashboard data
axios.get('/api/admin/dashboard')
  .then(res => console.log(res.data))
  .catch(err => console.error(err))

This routes all /api requests from Vue to your PHP server, avoiding CORS errors entirely.

Production Environment

Two common deployment setups to choose from:

Setup 1: Bundle Vue Admin with PHP Server

  1. Build your Vue Admin project:
npm run build
  1. Copy the dist folder contents to your PHP server’s public directory (e.g., public/admin).
  2. Update API requests to use relative paths (e.g., /api/admin/dashboard). Since both run on the same domain, no CORS issues will occur.

Setup 2: Deploy Vue Admin & PHP Server Separately

Configure CORS on your PHP API to allow requests from your production Vue domain:
Add this to your PHP entry file (e.g., index.php):

header("Access-Control-Allow-Origin: https://your-production-vue-domain.com");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Credentials: true"); // Enable if using cookies/sessions

// Handle preflight OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  exit(0);
}

In your Vue axios config, enable credentials to pass cookies:

axios.defaults.withCredentials = true;

2. Route Auth Guard (Redirect Unauthenticated Users)

Use Vue Router’s global navigation guard to lock down all Admin routes:

Step 1: Mark Protected Routes

In your Admin Vue project’s router/index.js, add a meta field to routes that require login:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/admin/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/admin/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true } // Mark this route as protected
  },
  // Add all other Admin routes with `meta.requiresAuth: true`
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

Step 2: Add Global Navigation Guard

Add this code after the router definition in router/index.js:

router.beforeEach((to, from, next) => {
  // Check if the target route requires authentication
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // Verify login status (adjust this to match your auth logic)
    const isLoggedIn = localStorage.getItem('adminToken') !== null;

    if (!isLoggedIn) {
      // Redirect to login page if user isn't authenticated
      next({ name: 'Login' })
    } else {
      // Allow access to the protected route
      next()
    }
  } else {
    // For public routes (like login), proceed normally
    next()
  }
})

Step 3: Handle Login/Logout Logic

When the admin logs in successfully, store the auth token (from PHP API response) in localStorage (and Vuex, if you’re using it):

// Example login method in Login.vue
async handleLogin() {
  try {
    const response = await axios.post('/api/admin/login', {
      username: this.username,
      password: this.password
    });
    // Store token for future requests
    localStorage.setItem('adminToken', response.data.token);
    // Redirect to dashboard after login
    this.$router.push({ name: 'Dashboard' });
  } catch (error) {
    console.error('Login failed:', error);
  }
}

For logout, clear the token and redirect to login:

// Example logout method
handleLogout() {
  localStorage.removeItem('adminToken');
  this.$router.push({ name: 'Login' });
}

Bonus: Handle Token Expiry

Add an axios interceptor to catch 401 Unauthorized responses (token expired) and auto-redirect to login:

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      localStorage.removeItem('adminToken');
      router.push({ name: 'Login' });
    }
    return Promise.reject(error);
  }
);

内容的提问来源于stack exchange,提问作者opeolluwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:23:14