Just deployed my app on heroku for the first time. Everything runs smoothly with GET requests, but encountering an application error when attempting to make a POST request with a body.
After checking the logs on heroku, it appears that there is an issue with MongoDB authentication. Oddly enough, the code works fine when run locally. It's worth noting that I have allowed access from any IP using 0.0.0.0/0
Implemented a solution found online by setting up the headers in app.use like this:
app.use((req, res) => {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
})
This is the POST request in the Express app:
app.post('/newOrder', async (req, res) => {
res.header('Access-Control-Allow-Origin: *')
const { fullname, phone, textMsg, currentItems, total } = req.body
let message = []
let inputType = []
// Checking for validation of input fields
if (fullname.length === 0) {
const errMsg = 'This field cannot be empty'
message.push(errMsg)
inputType.push(0)
}
if (phone.length === 0) {
const errMsg = 'This field cannot be empty'
message.push(errMsg)
inputType.push(1)
}
if (!(/^[a-zA-Z\u0590-\u05FF\s]+$/.test(fullname))) {
const errMsg = 'Full name must contain only letters and spaces'
message.push(errMsg)
inputType.push(0)
}
// more validations...
if (inputType.length !== 0) {
return res.status(400).json({
message,
inputType
})
}
// Creating new ticket and saving to database
const newTicket = new Ticket({
fullname,
phone,
textMsg,
items: currentItems.map((data) => data.desc),
total
})
await newTicket.save()
.then(async (order) => {
// Sending mail after saving order
const isMailSent = await mailTicket(fullname, phone, textMsg, currentItems, total, order)
if (!isMailSent) {
return res.status(400).json({
mailError: true,
message: 'Temporary error in sending the order to the designer - contact designer directly'
})
}
return res.status(200).json({
orderId: order._id
})
})
})
Any ideas on what might be causing this issue?