首页 > 解决方案 > Cors“不存在'Access-Control-Allow-Origin'标头”问题

问题描述

我正在尝试解决我的 express 服务器上发生的这个 CORS 错误。我已经实现了 npm CORS 包,通过启用所有来源的 CORS 请求来解决这个问题,但是我没有成功并且一直面临这个错误:

CORS 错误

Github 存储库

应用程序.js

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const queries = require("./queries");
const port = process.env.PORT || 3001;

app.use(express.static("public"));
app.use(cors());
app.use(bodyParser.json());

app.get("/questions", (req, res) => {
    queries.getAllQuestions().then((questions) => res.send(questions));
});

app.get("/questions/:id", (req, res) => {
    queries
        .getQuestionById(req.params.id)
        .then((question) => res.send(question));
});

app.get("/answers", (req, res) => {
    queries.getAllAnswers().then((answers) => res.send(answers));
});

app.get("/answers/:id", (req, res) => {
    queries.getAnswerById(req.params.id).then((answer) => res.send(answer));
});

app.get("/users", (req, res) => {
    queries.getAllUsers().then((users) => res.send(users));
});

app.get("/users/:id", (req, res) => {
    queries.getUserById(req.params.id).then((user) => res.send(user));
});

app.post("/questions", (req, res) => {
    queries
        .createQuestion(req.body)
        .then((newQuestion) => res.send(newQuestion));
});

app.post("/answers", (req, res) => {
    queries.createAnswer(req.body).then((newAnswer) => res.send(newAnswer));
});

app.delete("/questions/:id", (req, res) => {
    queries.deleteQuestion(req.params.id).then(res.sendStatus(204));
});

app.delete("/answers/:id", (req, res) => {
    queries.deleteAnswer(req.params.id).then(res.sendStatus(204));
});

app.delete("/users/:id", (req, res) => {
    queries.deleteUser(req.params.id).then(res.sendStatus(204));
});

app.patch("/questions/:id/upvote", (req, res) => {
    queries
        .patchUpvoteQuestion(req.params.id)
        .then((newVoteCount) => res.send("post"));
});

app.patch("/questions/:id/downvote", (req, res) => {
    queries
        .patchDownvoteQuestion(req.params.id)
        .then((newVoteCount) => res.send("post"));
});

app.patch("/answers/:id/upvote", (req, res) => {
    queries
        .patchUpvoteAnswer(req.params.id)
        .then((newVoteCount) => res.send("it worked"));
});

app.patch("/answers/:id/downvote", (req, res) => {
    queries
        .patchDownvoteAnswer(req.params.id)
        .then((newVoteCount) => res.send("it worked"));
});

app.listen(port, () => {
    console.log(`listening on ${port}`);
});

我已经尝试过:

app.use(cors());

app.use(cors({ origin: true }));

app.use(cors({ origin: "*" }));

标签: javascriptnode.jsexpresscors

解决方案


1.使用cors中间件

app.use(cors)

2.自定义中间件

app.use((req, res, next) => {
      if(req.method == "OPTIONS") {
          res.sendStatus(200)
      }
      
      next()
  })

推荐阅读