将我的 MERN 堆栈项目的服务器代码从 localhost 部署到 vercell 后,它显示此错误!怎么解决?
从源“https://bloodcare-bangladesh.web.app”获取“https://blood-management-server.vercel.app/donor”的访问已被 CORS 策略阻止:对预检请求的响应不会”通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
客户端代码:
const handleDonorRegistration = event => {
event.preventDefault();
const image = event.target.files;
const name = event.target.name.value;
const email = event.target.email.value;
const phone = event.target.phone.value;
const bloodGroup = event.target.bloodGroup.value;
const birthday = event.target.birthday.value;
const lastDonationDate = event.target.lastDonationDate.value;
const donorWeight = event.target.donorWeight.value;
const height = event.target.height.value;
const countryName = event.target.countryName.value;
const districtName = event.target.districtName.value;
const donor = {image, name, email, phone, bloodGroup, gender, birthday, lastDonationDate, donorWeight, height, countryName, districtName }
fetch('https://blood-management-server.vercel.app/donor', {
method: 'POST',
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(donor)
})
.then(res => res.json())
.then(data => {
Swal.fire({
title: "Congratulations!",
text: "You are in the donor list!",
icon: "success"
});
event.target.reset();
})
}
服务器代码:
const express = require("express");
const { MongoClient, ServerApiVersion } = require("mongodb");
const cors = require("cors");
const {} = require("mongodb");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
//Middleware
const corsOptions = {
origin: "https://bloodcare-bangladesh.web.app",
methods: ["GET", "POST"],
allowedHeaders: ["Content-Type"],
};
app.use(cors(corsOptions));
app.use(express.json());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://bloodcare-bangladesh.web.app');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
const uri = `mongodb+srv://${process.env.BD_USER}:${process.env.DB_PASS}@bloodcare-bd.gduqg86.mongodb.net/?retryWrites=true&w=majority`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
client.connect();
const database = client.db("userDB");
const userCollections = database.collection("users");
const donorCollection = client.db("userDB").collection("donors");
app.get("/donors", async (req, res) => {
const query = {};
const cursor = donorCollection.find(query);
const donors = await cursor.toArray();
res.send(donors);
});
app.post("/user", async (req, res) => {
const user = req.body;
console.log("new user added:", user);
const result = await userCollections.insertOne(user);
});
app.post("/donor", async (req, res) => {
const donor = req.body;
console.log("added new Donor:", donor);
const result = await donorCollection.insertOne(donor);
res.send(result);
});
// Send a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log(
"Pinged your deployment. You successfully connected to MongoDB!"
);
} finally {
// Ensures that the client will close when you finish/error
// await client.close();
}
}
run().catch(console.log);
app.get("/", (req, res) => {
res.send("server is running for blood management....!");
});
app.options('*', cors(corsOptions));
app.listen(port, () => {
console.log(`Curd server is running on port ${port}`);
});
从错误消息和您的服务器代码来看,您似乎只列出了
Content Type
作为服务器允许的标头:
const corsOptions = {
origin: "https://bloodcare-bangladesh.web.app",
methods: ["GET", "POST"],
allowedHeaders: ["Content-Type"],
};
但随后您再次向下设置标题:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://bloodcare-bangladesh.web.app');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
所以,这很可能是由于不一致而导致的错误。
修复: 将
cors
包用于所有 CORS 配置,如果您想使用这些额外标头,请将其添加到 allowedHeaders
中的 corsOptions
。
让我知道这是否有效。