【问题标题】:ExpressJS: Request has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resourceExpressJS:请求已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2019-03-15 12:57:21
【问题描述】:

在我的浏览器开发人员工具栏中,我收到以下关于 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();
    });

有谁知道为什么现在被屏蔽了

【问题讨论】:

  • 只是为了确定,哪个端口正在使用该中间件代码?还要确保你把它放在路线之前
  • 我在哪里看到的?
  • 您有一台服务器正在监听http://localhost:8000,另一台正在监听http://localhost:3000 我只是想确保中间件在监听http://localhost:8000 的服务器中。还要确保在路由之前定义中间件

标签: node.js express next.js


【解决方案1】:

最好如下使用“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;

【讨论】:

    猜你喜欢
    • 2020-01-24
    • 2021-12-27
    • 2019-12-05
    • 1970-01-01
    • 2020-04-16
    • 2021-04-28
    • 2022-06-21
    • 2022-07-19
    • 2021-04-14
    相关资源
    最近更新 更多