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

前端与后端连接时遭遇CORS策略错误,无法获取后端数据

解决CORS策略:No 'Access-Control-Allow-Origin' header 错误

后端配置(生产环境首选)

根据后端使用的语言/框架,核心是在响应头中添加Access-Control-Allow-Origin,以下是几种常见框架的配置方式:

  • Node.js/Express:使用cors中间件
const express = require('express');
const cors = require('cors');
const app = express();

// 允许指定前端域名(比如你的localhost:3000)
app.use(cors({ origin: 'http://localhost:3000' }));

// 开发环境临时允许所有域名(生产环境禁用)
// app.use(cors());
  • Python/Django:在settings.py中配置
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
]

// 开发环境临时允许所有(生产禁用)
// CORS_ALLOW_ALL_ORIGINS = True
  • Java/Spring Boot:单个接口或全局配置
// 单个接口允许指定域名访问
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/your-endpoint")
public ResponseEntity<?> getData() {
    // 业务逻辑
}

// 全局配置所有接口
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

前端开发环境临时代理(仅开发阶段用)

如果后端暂时无法修改配置,可以在前端项目中设置代理转发请求:

  • React(Create React App):在package.json中添加代理配置
"proxy": "https://nms.urinboydev.uz/"

之后前端请求改为fetch('/api/your-path'),会自动转发到目标后端地址。

  • Vue(Vue CLI):在vue.config.js中配置
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'https://nms.urinboydev.uz/',
        changeOrigin: true,
        pathRewrite: { '^/api': '' }
      }
    }
  }
}

请求时使用axios.get('/api/your-path')即可。

额外注意

  • 生产环境禁止使用*允许所有域名访问,必须指定具体的前端域名,避免安全隐患。
  • 如果后端通过Nginx托管,可在Nginx配置中添加响应头:
location / {
    add_header Access-Control-Allow-Origin http://localhost:3000;
    add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
    add_header Access-Control-Allow-Headers 'Content-Type';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:42:19