centos

如何在CentOS上配置Node.js的跨域资源共享(CORS)

小樊
42
2025-10-17 12:01:29
栏目: 编程语言

在CentOS上配置Node.js的跨域资源共享(CORS)可以通过多种方式实现,以下是几种常见的方法:

方法一:使用Express框架

如果你使用的是Express框架,可以通过中间件来处理CORS。

  1. 安装Express和CORS中间件

    npm install express cors
    
  2. 配置Express应用

    const express = require('express');
    const cors = require('cors');
    
    const app = express();
    
    // 允许所有域名访问
    app.use(cors());
    
    // 或者只允许特定域名访问
    // app.use(cors({
    //   origin: 'http://example.com'
    // }));
    
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
    

方法二:手动设置响应头

如果你不想使用中间件,可以手动设置响应头来处理CORS。

const http = require('http');

const server = http.createServer((req, res) => {
  // 设置允许跨域的域名
  res.setHeader('Access-Control-Allow-Origin', '*');
  // 设置允许的HTTP方法
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  // 设置允许的请求头
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    return res.end();
  }

  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World!');
});

server.listen(3000, () => {
  console.log('Server is running on port 3000');
});

方法三:使用Nginx反向代理

如果你使用Nginx作为反向代理服务器,可以在Nginx配置文件中设置CORS。

  1. 编辑Nginx配置文件(通常位于/etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf):

    server {
        listen 80;
        server_name yourdomain.com;
    
        location / {
            proxy_pass http://localhost:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
    
            add_header 'Access-Control-Allow-Origin' '*' always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
            add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always;
    
            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
                add_header 'Content-Length' 0;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                return 200;
            }
        }
    }
    
  2. 重启Nginx

    sudo systemctl restart nginx
    

通过以上几种方法,你可以在CentOS上配置Node.js的跨域资源共享(CORS)。选择适合你项目需求的方法进行配置即可。

0
看了该问题的人还看了