Angular4-5代理服务器实现问询:解决前后端跨域请求问题
Hey, I’ve dealt with this exact cross-origin problem when working with Angular 5 and the CLI—let’s walk through setting up a proxy server to get your frontend talking to the backend smoothly:
Step 1: Create a Proxy Configuration File
In your project’s root directory (same level as package.json and angular-cli.json), make a new file called proxy.conf.json with this content:
{ "/api": { "target": "http://localhost:8000", "secure": false, "changeOrigin": true, "pathRewrite": { "^/api": "" } } }
Let me break down what each part does:
"/api": This is the prefix your frontend will use for API requests. Any request starting with/apiwill be routed through the proxy."target": Your backend server’s base URL (http://localhost:8000in your case)."secure": false: Skips SSL certificate checks (safe for local development)."changeOrigin": true: Adjusts theHostheader in the proxied request to match the target server—this fixes issues where some backends block requests with mismatched Host values."pathRewrite": Removes the/apiprefix from the request before sending it to the backend. So a frontend request to/api/users/getuserinfogets converted tohttp://localhost:8000/users/getuserinfo.
Step 2: Update Your Development Server Command
Open your package.json file and modify the start script to include the proxy config:
"scripts": { "start": "ng serve --proxy-config proxy.conf.json", // ... other scripts }
Alternatively, if you prefer using angular-cli.json (common in Angular 4/5), add the proxyConfig property under the defaults -> serve section:
"defaults": { "serve": { "proxyConfig": "proxy.conf.json" }, // ... other defaults }
Step 3: Adjust Frontend API Requests
Update all your HTTP calls in the Angular app to use the /api prefix instead of the full backend URL. For example:
Before:
this.http.get('http://localhost:8000/users/getuserinfo').subscribe(...);
After:
this.http.get('/api/users/getuserinfo').subscribe(...);
Step 4: Test It Out
Stop your running ng serve instance, then restart it with the updated start command (npm start or ng serve --proxy-config proxy.conf.json). Now when your frontend makes API requests, they’ll be routed through the Angular CLI’s proxy server, bypassing the CORS error.
This setup works great for local development—when you deploy to production, you’ll want to handle CORS either via your backend (adding CORS headers) or using a reverse proxy like Nginx, but this proxy is perfect for getting your dev environment up and running quickly.
内容的提问来源于stack exchange,提问作者Vinod

