You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Node.js 14环境下REST API的CORS跨域问题解决方案咨询

Fixing Your Node.js/Express CORS Issue

Hey there, let's get that CORS error sorted out for you! The problem here is actually super straightforward—your CORS middleware is being applied after your routes, which means the response from your /feed/posts endpoint never gets the required CORS headers attached.

Let's Break Down the Error First

Your browser is throwing this because the response from http://localhost:8080 doesn't include the Access-Control-Allow-Origin header:

Access to fetch at 'http://localhost:8080/feed/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The Fix: Reorder Your Middleware

Express runs middleware in the order you define them. Right now, you're mounting your /feed routes first, then adding the CORS middleware. That means when a request hits /feed/posts, your route handles it and sends a response before the CORS middleware ever gets to run.

Just move your CORS middleware block before your route mount, like this:

const express = require('express');
const bodyParser = require('body-parser');
const feedRoutes = require('./routes/feed');
const app = express();

// 1. Parse incoming request bodies first
app.use(bodyParser.json());

// 2. Apply CORS headers BEFORE handling routes
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});

// 3. Now mount your routes
app.use('/feed', feedRoutes);

app.listen(8080);

Bonus: Use the Official cors Package (Optional)

If you want to simplify things (and avoid manual header setup for more complex scenarios), you can use the official cors npm package:

  1. Install it first:
    npm install cors
    
  2. Update your code to use it:
    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    const feedRoutes = require('./routes/feed');
    const app = express();
    
    app.use(bodyParser.json());
    // This single line replaces your custom CORS middleware
    app.use(cors());
    
    app.use('/feed', feedRoutes);
    
    app.listen(8080);
    

The cors package handles all the edge cases (like preflight OPTIONS requests) automatically, which is great as your API grows.

Quick Check

After making this change, restart your Node.js server and refresh your React app—your /feed/posts request should now work without the CORS error.

Your Node.js (v14.17.0) and npm (7.18.1) versions are totally compatible with this fix, so no issues there.

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

火山引擎 最新活动