I am using mongodb, with NodeJS ORM, mongoose, A modelis shown below
const mongoose = require('mongoose');
const userFeedbackIdsSchema = new mongoose.Schema({
feedbackId: { type: String, unique: true },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
// other fields...
});
module.exports = mongoose.model('UserFeedbackIds', userFeedbackIdsSchema);
With following endpoint
router.post('/generateId', async (req, res) => {
const { userId } = req.body;
if (!userId) {
return res.status(400).json({ error: 'User ID is required' });
}
let uniqueId;
let isUnique = false;
while (!isUnique) {
uniqueId = generateUniqueId(8);
const existingFeedback = await UserFeedback.findOne({ feedbackId: uniqueId });
if (!existingFeedback) {
isUnique = true;
}
}
const newFeedback = new UserFeedback({ feedbackId: uniqueId, userId });
await newFeedback.save();
res.json({ uniqueId });
})
When I called the endpoint with a dummyvalue,
const response = await axios.post(`${API_ADDRESS}/users/generateId`, { userId: 'dummytest' });
The following cors error was thrown
Access to XMLHttpRequest at ‘site-address/users/generate-id/’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I had defined the cors
app.use(cors({
origin: 'http://localhost:3000', // Allow requests from this origin
methods: ['GET', 'POST'], // Allow these HTTP methods
credentials: true // Allow cookies to be sent
}));
My question is, how come the cors issue was raised; on wrong data value, the issue was resolved once the correct data value was passed.