Hi,
I have two problem with my deployed website that made by Next.js, and in local machine I don’t have these problems and everything works well:
- I have a form in contact page that send POST request to /api/contact. On the Netlify when the form is submitted, it’s work perfectly and the form data stored on MongoDB but returned error code 502.
/api/contact.js
import { connectDatabase, insertDocument } from '../../lib/mongodb-utils';
import { storeContactsData } from '../../lib/store-utils';
async function handler(req, res) {
if (req.method === 'POST') {
let client;
const newFormData = {
date: new Date().toISOString(),
name: req.body.name,
email; req.body.email,
message: req.body.message,
};
try {
client = await connectDatabase();
} catch (err) {
res.status(500).json({ message: 'Connecting to the database failed.' });
return;
}
try {
await insertDocument(client, 'forms', newFormData);
res
.status(201)
.json({ message: 'Successfully stored message.', data: newFormData });
} catch (err) {
res.status(500).json({ message: 'Storing message failed.' });
client.close();
return;
}
client.close();
}
}
export default handler;
- For search bar I fetch data on /api/data?action=query&doc=articles&fields=title&fields=slug and I have error 500 but if I remove query fields it’s returned whole documents and work well (I don’t have query fields problem in development and production).
/api/data.js
import {
connectDatabase,
getAllDocuments,
getChunkOfAllPosts,
} from '../../lib/mongodb-utils';
async function handler(req, res) {
let result, client;
if (req.method === 'GET') {
const { action, doc, fields } = req.query;
if (action === 'query') {
try {
client = await connectDatabase();
} catch (err) {
res.status(500).json({ message: 'Connecting to the database failed.' });
}
if (fields) {
const requiredFields = {}; // The object required to project fields in MongoDB
fields.forEach(field => {
requiredFields[field] = 1;
});
try {
result = await getChunkOfAllPosts(client, {}, requiredFields);
} catch (err) {
res.status(404).json({ message: 'Queried data not found.' });
client.close();
}
} else {
try {
result = await getAllDocuments(client, 'posts', {});
} catch (err) {
res.status(404).json({ message: 'Queried data not found.' });
client.close();
}
}
client.close();
res.status(200).json({ message: 'Data query was successful.', result });
}
}
}
export default handler;
I used MongoDB database and it accept all IP address.