【问题标题】:Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy从源“http://localhost:3000”访问“http://localhost:8080/”的 XMLHttpRequest 已被 CORS 策略阻止
【发布时间】:2021-10-05 05:05:26
【问题描述】:

完全错误: “从源 'http://localhost:3000' 访问 XMLHttpRequest 在 'http://localhost:8080/api/tutorials' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否'请求的资源上存在 Access-Control-Allow-Origin' 标头。"

在前端我使用的是 NuxtJS。我正在 localhost:3000 上托管的节点服务器上发送一个简单的发布请求,但即使我在我的应用程序中使用 CORS,它也会给我这个错误。该请求用于在 mongodb 数据库中插入数据。

在节点服务器上,即 localhost:8080,我试过了:

var corsOptions = {
  origin: "http://localhost:3000",
};

app.use(cors(corsOptions));

也试过了,但没有成功:

app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");

  next();
});

请告知是否有解决此错误的方法。谢谢。

已编辑:

在这里,我使用 axios 首先创建一个实例(在前端)。 https://ibb.co/C2ChH5d

这些都是我想要使用的请求。 https://ibb.co/5TbSHjF

这是当前正在发出的请求(创建)。 https://ibb.co/pPp8rdh

nodeJS代码:https://ibb.co/GFWMQW1

NodeJS 代码:

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

const app = express();

require("./app/routes/tutorial.routes")(app);

var corsOptions = {
  origin: "http://localhost:3000",
};

app.options("*", cors());

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(bodyParser.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

const db = require("./app/models");
db.mongoose
  .connect(db.url, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Connected to the database!");
  })
  .catch((err) => {
    console.log("Cannot connect to the database!", err);
    process.exit();
  });

【问题讨论】:

  • 这两次尝试解决您的问题 - 您是在哪个服务器上设置的? 8080 还是 3000?
  • 在节点服务器上,即 8080,因为正在从那里访问资源。当我通过邮递员发送请求时,它没有给出这个错误。
  • 是的,邮递员不受 CORS 的限制 - 所以,使用 :3000 加载的代码在 :8080 发出 api 请求,它是 :8080 具有 use(cors) ...你能显示发出请求的代码
  • 错误消息显示 preflight 这在您正在使用的模块的手册中有所介绍:npmjs.com/package/cors#enabling-cors-pre-flight
  • @Quentin 我是 nodejs 的新手。请告诉我必须使用哪个代码。我已经尝试过这个 'app.options('*', cors())' 但仍然给出同样的错误

标签: javascript node.js express cors


【解决方案1】:

好吧,问题是我在初始化 cors() 之前使用了 API 路由。当我将路线向下移动到app.use(cors(corsOptions)) 时,问题就解决了。

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 2021-03-08
    • 2021-12-18
    • 1970-01-01
    • 2021-04-12
    • 2021-07-03
    • 1970-01-01
    • 2020-11-11
    • 2019-11-11
    相关资源
    最近更新 更多