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.
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.
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
OPTIONSrequests
Many backend frameworks don't automatically handleOPTIONSrequests (the preflight check). You'll need to add CORS support explicitly:- For Node.js/Express: Use the
corsmiddleware, 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
@CrossOriginannotation 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); } }
- For Node.js/Express: Use the
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 (likeAuthorization), 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 theOPTIONSrequest—since preflight requests don't include auth tokens. You'll need to modify the interceptor to skip checkingOPTIONSrequests:// 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 } });
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:
- Add a
proxyConfigentry to yourangular.jsonunderarchitect > serve > options:"proxyConfig": "src/proxy.conf.json" - Create
src/proxy.conf.jsonwith:{ "/api/*": { "target": "https://your-api-server.com", "secure": false, "changeOrigin": true } } - Restart your Angular dev server—now calls to
/api/your-endpointwill be forwarded to the API server without CORS errors.
内容的提问来源于stack exchange,提问作者Austin

