javascript - Cors“不存在'Access-Control-Allow-Origin'标头”问题
问题描述
我正在尝试解决我的 express 服务器上发生的这个 CORS 错误。我已经实现了 npm CORS 包,通过启用所有来源的 CORS 请求来解决这个问题,但是我没有成功并且一直面临这个错误:
应用程序.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: "*" }));
解决方案
1.使用cors中间件
app.use(cors)
2.自定义中间件
app.use((req, res, next) => {
if(req.method == "OPTIONS") {
res.sendStatus(200)
}
next()
})
推荐阅读
- typescript - 如何访问 cypress/Typescript 中 cy.get() 中定义的值?
- java - 为什么在提供 lambda 参数时必须捕获异常?
- c - 合并排序中的一个错误
- php - 使用“#”作为路径参数的 CodeIgniter URI 路由
- java - 一个字符串可以在java中保存的最大数据量
- android - 如何为 EditText 的软键盘的 EnterKey 定义自定义操作?
- ansible - 在 Ansible 中使用列表键值
- c# - 适用于 ms 视觉工作室 2019 的 SAP B1 工作室
- python - 在另一个类中声明和更改类实例
- mongodb - MongoDB 查找按字符串 dateTime 排序的对象