Vue Cli项目对接远程PHP API实现Admin路由登录拦截方案咨询
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:
- Create/modify
vue.config.jsin 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 } } } } }
- In your Vue code (e.g., axios requests), use
/apias 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
- Build your Vue Admin project:
npm run build
- Copy the
distfolder contents to your PHP server’s public directory (e.g.,public/admin). - 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

