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

跨域请求被CORS策略拦截求助:localhost端口间请求失败

Fixing CORS Error Between React (localhost:3000) and Your API (localhost:3001)

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:

  1. Allow your frontend’s origin (http://localhost:3000)
  2. Enable credentials support
  3. Handle preflight OPTIONS requests (the browser sends this automatically before your actual POST request)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:21:25