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

请求资源无Access-Control-Allow-Origin头致跨域访问被拒求助

Hey there! Let’s figure out this CORS error and get your API requests working smoothly.

What’s causing this error?

You’re hitting a Cross-Origin Resource Sharing (CORS) issue, which stems from the browser’s same-origin policy. This policy blocks web pages from requesting resources from a different "origin" (a combination of protocol, domain, and port).

In your case, your frontend runs at http://localhost:8100, while your backend API is at http://localhost:9000 (or 8000, as seen in the error). Since the ports are different, they count as separate origins. The browser blocks the request because your backend hasn’t sent the Access-Control-Allow-Origin header to explicitly permit your frontend’s origin.

How to fix it

Here are the most common solutions, depending on your setup:


1. Configure CORS on your backend

This is the most direct fix—update your backend to allow requests from http://localhost:8100. Here’s how to do it for popular frameworks:

Node.js + Express

First, install the cors middleware:

npm install cors

Then add it to your Express app:

const express = require('express');
const cors = require('cors');
const app = express();

// Allow only your frontend origin (recommended)
app.use(cors({
  origin: 'http://localhost:8100'
}));

// For development only: allow all origins (not safe for production)
// app.use(cors());

// Your API route
app.get('/api/post', (req, res) => {
  // Handle request and return data
  res.json({ message: 'Post data here' });
});

app.listen(9000, () => console.log('Server running on port 9000'));
Python + Django

Install the django-cors-headers package:

pip install django-cors-headers

Update your settings.py:

INSTALLED_APPS = [
    # ... other apps
    'corsheaders',
]

MIDDLEWARE = [
    # Place this before CommonMiddleware
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    # ... other middleware
]

# Allow your frontend origin
CORS_ALLOWED_ORIGINS = [
    "http://localhost:8100",
]

# Dev-only: allow all origins
# CORS_ALLOW_ALL_ORIGINS = True
Java + Spring Boot

Option 1: Add @CrossOrigin to your controller:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "http://localhost:8100")
public class PostController {
    @GetMapping("/api/post")
    public String getPosts() {
        return "Sample post data";
    }
}

Option 2: Global CORS configuration:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:8100")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

2. Use a reverse proxy (e.g., Nginx)

If modifying the backend isn’t an option, use Nginx to proxy both your frontend and API under the same origin. This tricks the browser into thinking they’re from the same source.

Here’s a sample Nginx config:

server {
    listen 80;
    server_name localhost;

    # Serve frontend from port 8100
    location / {
        proxy_pass http://localhost:8100;
    }

    # Proxy API requests to port 9000
    location /api/ {
        proxy_pass http://localhost:9000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Now your frontend can request /api/post instead of the full URL, and Nginx will forward it to the backend—no CORS errors!


3. Frontend dev server proxy (for development only)

Most modern frontend frameworks include built-in proxy tools to bypass CORS during development:

Vue (vue-cli)

Add this to vue.config.js:

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:9000',
        changeOrigin: true
      }
    }
  }
}
React (create-react-app)

Add this line to your package.json:

"proxy": "http://localhost:9000"
Angular

Create src/proxy.conf.json:

{
  "/api": {
    "target": "http://localhost:9000",
    "secure": false
  }
}

Then update angular.json under architect > serve > options:

"proxyConfig": "src/proxy.conf.json"

Important note for production

Never set CORS_ALLOW_ALL_ORIGINS = true or allow all origins in production. Always specify exact frontend domains to avoid security risks.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:20:35