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

Angular4-5代理服务器实现问询:解决前后端跨域请求问题

Fixing CORS Issues with Angular 4/5 CLI Proxy Setup

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 /api will be routed through the proxy.
  • "target": Your backend server’s base URL (http://localhost:8000 in your case).
  • "secure": false: Skips SSL certificate checks (safe for local development).
  • "changeOrigin": true: Adjusts the Host header in the proxied request to match the target server—this fixes issues where some backends block requests with mismatched Host values.
  • "pathRewrite": Removes the /api prefix from the request before sending it to the backend. So a frontend request to /api/users/getuserinfo gets converted to http://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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:21:26