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

Angular报错:Failed to load resource: Preflight response was not successful含义与解决方法

Hey there! Let's unpack this error and get your Angular API call working smoothly.

What Does "Failed to load resource: Preflight response was not successful" Mean?

This error ties directly to CORS (Cross-Origin Resource Sharing)—the browser's built-in security mechanism that blocks requests from one domain to another by default.

When your Angular app (say, running on localhost:4200) tries to hit an API hosted on a different domain (like https://your-api-server.com), the browser first sends a preflight OPTIONS request. Think of this as a "test check" to ask the server: "Hey, am I allowed to send my actual request here?"

If that preflight request doesn't get a successful 2XX response (like 200 OK) or the server doesn't return the required CORS headers, the browser stops the real request dead in its tracks and throws this error.

Common Fixes

Most of the time, the issue is on the server side—you need to configure it to handle CORS properly. Here's how to fix it for common backend setups:

  • Server isn't handling OPTIONS requests
    Many backend frameworks don't automatically handle OPTIONS requests (the preflight check). You'll need to add CORS support explicitly:

    • For Node.js/Express: Use the cors middleware, which automatically handles preflight requests and sets the right headers:
      const express = require('express');
      const cors = require('cors');
      const app = express();
      
      // Allow your Angular app's origin (replace with your actual domain in production)
      app.use(cors({ origin: 'http://localhost:4200' }));
      
    • For Spring Boot: Add a global CORS config or use the @CrossOrigin annotation on your controllers:
      @Configuration
      public class CorsConfig implements WebMvcConfigurer {
          @Override
          public void addCorsMappings(CorsRegistry registry) {
              registry.addMapping("/**")
                      .allowedOrigins("http://localhost:4200")
                      .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                      .allowedHeaders("*")
                      .allowCredentials(true);
          }
      }
      
  • Missing or incomplete CORS response headers
    Make sure your server returns these critical headers in its preflight response:

    • Access-Control-Allow-Origin: Specifies which domains are allowed (use your Angular app's URL, or * for all—though * isn't recommended for production if you're using credentials).
    • Access-Control-Allow-Methods: Lists the HTTP methods (GET, POST, etc.) allowed for cross-origin requests.
    • Access-Control-Allow-Headers: If your Angular request uses custom headers (like Authorization), this header needs to include them.
  • Auth interceptors blocking preflight requests
    If your backend uses an auth interceptor (like JWT token checks), it might block the OPTIONS request—since preflight requests don't include auth tokens. You'll need to modify the interceptor to skip checking OPTIONS requests:

    // Example for Express
    app.use((req, res, next) => {
        if (req.method === 'OPTIONS') {
            res.sendStatus(200); // Allow preflight requests
        } else {
            next(); // Proceed with auth checks for other requests
        }
    });
    
Local Development Workaround (Not for Production)

If you're just testing locally, you can set up an Angular proxy to avoid CORS issues entirely. This forwards your API requests from the Angular dev server to the API server, making it look like they're coming from the same domain:

  1. Add a proxyConfig entry to your angular.json under architect > serve > options:
    "proxyConfig": "src/proxy.conf.json"
    
  2. Create src/proxy.conf.json with:
    {
      "/api/*": {
        "target": "https://your-api-server.com",
        "secure": false,
        "changeOrigin": true
      }
    }
    
  3. Restart your Angular dev server—now calls to /api/your-endpoint will be forwarded to the API server without CORS errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:04:56