跨域请求被CORS策略拦截求助:localhost端口间请求失败
This is a classic CORS issue, and the fix needs to happen on your backend—your frontend's withCredentials setting is correct, but it won’t work unless the server sends the right response headers to satisfy the browser’s cross-origin security checks.
What’s Causing the Error?
The browser blocks your request because your API isn’t returning the required Access-Control-Allow-Origin header. When making cross-origin requests (especially with credentials enabled via withCredentials: true), the server must explicitly:
- Allow your frontend’s origin (
http://localhost:3000) - Enable credentials support
- Handle preflight
OPTIONSrequests (the browser sends this automatically before your actualPOSTrequest)
Solution (Express.js Backend)
Since you’re using Express router syntax, the easiest way to resolve this is with the official cors middleware, which handles all CORS logic automatically.
Step 1: Install the cors Package
Run this in your backend project folder:
npm install cors
Step 2: Configure and Apply the Middleware
Update your main Express app file (where you initialize the server) to include the CORS setup:
const express = require('express'); const cors = require('cors'); const app = express(); // Configure CORS to allow your frontend and credentials const corsOptions = { origin: 'http://localhost:3000', // Explicitly allow your React app's origin credentials: true, // Required to match your frontend's withCredentials: true allowedHeaders: ['Content-Type', 'auth'] // Allow custom headers your request uses }; // Apply the middleware before your routes app.use(cors(corsOptions)); // Mount your login router here app.use(router); app.listen(3001, () => { console.log('API running on http://localhost:3001'); });
Alternative: Manual Header Setup (No Middleware)
If you prefer not to use a package, you can manually add the headers and handle preflight requests:
// Add this before your router is mounted app.use((req, res, next) => { // Allow your frontend origin res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); // Enable credentials support res.setHeader('Access-Control-Allow-Credentials', 'true'); // Allow headers used in your request res.setHeader('Access-Control-Allow-Headers', 'Content-Type, auth'); // Allow HTTP methods your app uses res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); // Handle preflight OPTIONS request immediately if (req.method === 'OPTIONS') { return res.sendStatus(200); } next(); });
Why Your Previous Attempt Didn’t Work
Setting xhr.withCredentials = true tells the browser to send cookies/credentials with the request, but this alone isn’t enough. The browser will still block the response unless the server explicitly allows your origin and credentials via the required headers.
内容的提问来源于stack exchange,提问作者Stan

