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

AWS EC2部署Node.js+MongoDB网站遇跨域请求失败问题求助

Fixing Cross-Origin Request Errors on Your AWS EC2 Node.js Site

Hey there! That cross-origin error you're hitting is super common when your frontend and backend live on different origins (like your local browser trying to talk to your EC2-hosted backend). Let's walk through how to fix this step by step:

1. Use the cors Middleware (Quickest Solution)

The easiest way to handle CORS in Node.js/Express is with the official cors package. Here's how to set it up:

  • First, install the package in your project folder:
    npm install cors
    
  • Then, import and enable it in your Express app:
    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    // Allow all origins (great for development testing)
    app.use(cors());
    
    // For production, lock it down to your specific frontend domain (more secure)
    // app.use(cors({
    //   origin: 'https://your-frontend-domain.com' // Replace with your actual frontend URL
    // }));
    
    // Rest of your route setup and server initialization
    app.listen(3001, () => {
      console.log('Server running on port 3001');
    });
    

2. Manually Set CORS Headers (No Third-Party Package)

If you'd rather avoid adding a dependency, you can create a custom middleware to set the required HTTP headers:

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

app.use((req, res, next) => {
  // Allow your frontend's origin (use '*' for development, or your actual frontend URL for production)
  res.header('Access-Control-Allow-Origin', '*');
  // Permit common HTTP methods
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  // Allow common request headers
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  
  // Handle preflight OPTIONS requests (browsers send these before real requests)
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  
  next();
});

// Your routes here
app.listen(3001, () => {
  console.log('Server running on port 3001');
});

3. Double-Check Your Request URLs

Make sure your frontend is sending requests to the full URL including the protocol (http/https). For example:

  • Correct: http://ec2-54-173-21-43.compute-1.amazonaws.com:3001/api/your-endpoint
  • Incorrect: ec2-54-173-21-43.compute-1.amazonaws.com:3001/api/your-endpoint (missing http://)

Browsers need the protocol to properly identify if a request is cross-origin.

4. Verify EC2 Security Group Rules

Even though your NACLs are configured, don't skip checking your EC2 instance's security group:

  • Make sure there's an inbound rule allowing traffic on port 3001 from your local IP (or your frontend's IP range for production).
  • Avoid using 0.0.0.0/0 for port 3001 in production—it's safer to restrict access to trusted sources only.

After setting up the CORS configuration, restart your Node server and test those GET requests again. This should clear up the cross-origin blockage!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:03:37