【发布时间】:2021-08-05 04:46:17
【问题描述】:
我正在研究 Express.js 并以 JSON 格式发送数据。在无效端点上传递 POST、PATCH 请求时出现 CORS 错误(如下)。对于有效的 POST、PATCH 端点,没有 CORS 错误。 此外,对于无效/有效的 GET 端点请求,虽然没有 CORS 错误。
错误信息:
CORS 策略已阻止从源“https://www.google.com”获取“http://localhost:3000/invalid-endpoint”的访问权限:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。
我为无效的 POST 端点发送的获取命令:
fetch('http://localhost:3000/invalid-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
someValue: "999",
})
}).then(response => {
return response.json()}).then(data => {
console.log(data)}).catch(err => {
console.log(err)});
我的应用程序中包含的标题:
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
完整代码:
//require modules.
//Headers
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
//Endpoint Routes
app.use("/state", stateRoutes);
app.use("/district", districtRoutes);
app.use('/admin', adminRoutes);
app.use("/", stateDistrictRoutes); //also Home
/* All the invalid endpoints should fall into this. But CORS Error preventing that for POST and PATCH. GET is working fine here. */
app.use((req, res, next) => {
const error = new Error("Invalid Endpoint.")
error.status = 404;
throw error;
});
//All the errors should fall into this at last.
app.use((error, req, res, next) => {
const status = error.status || 500;
const message = error.message;
res.status(status).json({
status: status,
message: message,
info: error.data || null,
});
});
//connection to database....etc.
P.s.:- adminRoutes.js 页面 (/admin)。下面的 POST/PATCH 请求可以完美运行。
const express = require("express");
const router = express.Router();
const adminControllers = require("../controllers/adminController");
const adminAuthControllers = require("../controllers/adminAuthController");
router.post("/add/state", adminControllers.postState);
router.post("/add/district", adminControllers.postDistrict);
router.patch("/update/state/:state", adminControllers.patchState);
router.patch("/update/:state/:district", adminControllers.patchDistrict);
router.post("/login", adminAuthControllers.postLogin);
router.post("/signup", adminAuthControllers.postSignup);
module.exports = router;
adminControllers 页面
const State = require("../models/state");
const District = require("../models/district");
exports.postState = (req, res, next) => {
const body = req.body;
State.findOne({ name: req.body.name })
.then((data) => {
if (data) {
const error = new Error("State already Exists!");
error.status = 409;
throw error;
}
const state = new State({
...body,
creator: {
lastUpdatedBy: req.userEmail,
createdBy: req.userEmail,
},
});
return state.save();
})
.then((response) => {
res.status(201).json({
message: "State created Successfully!",
data: response,
});
})
.catch((err) => {
if (!err.status) {
err.status = 500;
}
next(err);
});
};
exports.postDistrict = (req, res, next) => {
const body = req.body;
District.findOne({
name: req.body.name,
state: req.body.state,
})
.then((data) => {
if (data) {
const error = new Error("District already Exists!");
error.status = 409;
throw error;
}
const district = new District({
...body,
creator: {
lastUpdatedBy: req.userEmail,
createdBy: req.userEmail,
},
});
return district.save();
})
.then((response) => {
res.status(201).json({
message: "District created Successfully!",
data: response,
});
})
.catch((err) => {
if (!err.status) {
err.status = 500;
}
next(err);
});
};
exports.patchState = (req, res, next) => {
const state = req.params.state;
const body = req.body;
State.findOneAndUpdate(
{ name: state },
{ ...body },
{
new: true,
}
)
.then((response) => {
res.status(200).json({
message: "State updated Successfully!",
data: response,
});
})
.catch((err) => {
if (!err.status) {
err.status = 500;
}
next(err);
});
};
exports.patchDistrict = (req, res, next) => {
const state = req.params.state;
const district = req.params.district;
const body = req.body;
District.findOneAndUpdate(
{ name: district, state: state },
{ ...body },
{
new: true,
}
)
.then((response) => {
res.status(200).json({
message: "District updated Successfully!",
data: response,
});
})
.catch((err) => {
if (!err.status) {
err.status = 500;
}
next(err);
});
};
谢谢! 保持安全。
【问题讨论】:
-
您能否显示您的一个路由模块的完整代码,其中涉及不会导致此类错误的有效 POST 或 PATCH 端点?
-
感谢@IAmDranged。我添加了一个 adminRoutes POST 端点。如果我使用正确的端点请求它可以正常工作,即localhost:3000/admin/add/state
-
能否请您只显示您的 adminRoutes 模块的完整代码?只是想看看那里实际设置的所有路线。
-
我已经添加了adminRoutes和adminControllers的完整代码。如果您需要更多信息,请告诉我。谢谢你:)
-
@IAmDranged 问题似乎出在 OPTIONS 上,它为无效的 POST/PATCH 端点提供 404。
标签: javascript rest express cors