Node.js ExpressJS:请求已被CORS策略阻止:否';访问控制允许原点';请求的资源上存在标头

Node.js ExpressJS:请求已被CORS策略阻止:否';访问控制允许原点';请求的资源上存在标头,node.js,express,next.js,Node.js,Express,Next.js,在“浏览器开发人员”工具栏中,我收到以下POST请求的错误消息: Access to XMLHttpRequest at 'http://localhost:8000/api/tags/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 但是,当我查看

在“浏览器开发人员”工具栏中,我收到以下POST请求的错误消息:

Access to XMLHttpRequest at 'http://localhost:8000/api/tags/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
但是,当我查看我的server.js时,我确实允许访问:

app.prepare().then(() => {
    const server = express();

    server.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });
有人知道为什么现在会阻止它吗?

最好使用下面的“cors”包

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());

// some route controllers
const customRoute = require('./customRoute.controller');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


// Custom routes
app.use('/api/tags', customRoute);

app.use(express.static(path.join(__dirname, 'dist')));


// Catch all other routes & return index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

module.exports = app;
最好使用“cors”包,如下所示

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());

// some route controllers
const customRoute = require('./customRoute.controller');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


// Custom routes
app.use('/api/tags', customRoute);

app.use(express.static(path.join(__dirname, 'dist')));


// Catch all other routes & return index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

module.exports = app;

只是为了确定,在哪个端口使用该中间件代码?还要确保你把它放在路由之前。我看到哪里了?你有一个服务器在监听
http://localhost:8000
和另一个正在收听
http://localhost:3000
我只想确保中间件位于侦听
http://localhost:8000
。还要确保在的路由可能的副本之前定义了中间件,以确保在哪个端口使用该中间件代码?还要确保你把它放在路由之前。我看到哪里了?你有一个服务器在监听
http://localhost:8000
和另一个正在收听
http://localhost:3000
我只想确保中间件位于侦听
http://localhost:8000
。还要确保中间件是在路由可能的复制之前定义的