首页 > 解决方案 > 从源“http://localhost:3000”访问“http://localhost:8080/”的 XMLHttpRequest 已被 CORS 策略阻止

问题描述

完全错误:“CORS 策略已阻止从源 'http://localhost:8080/api/tutorials' 访问 XMLHttpRequest:对预检请求的响应未通过访问控制检查:请求的资源上不存在“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

节点代码:

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();
  });

标签: javascriptnode.jsexpresscors

解决方案


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


推荐阅读