actually am not really experienced with netlify, i faced a problem in a function, it is really confusing,
I have made a website just for making it behave like an api, and it for now haves one function, which acts like a webservice for some website am trying to make, this is the function link:
https://omar-api.netlify.app/.netlify/functions/helpPP-webservice/add
So the code trying to connect to mongoDB atlas, the function when i run netlify dev which is test environment, it does connect to mongoDB to my db and it returns the data successfully, i’ve made some basic response to just test the database, and it worked on netlify dev the test environment, but when i published it on netlify it no longer work, so it works on the test environment, but when i publish it it does not work,
this is the code:
‘use strict’;
const { eventNames } = require(‘process’);
const { MongoClient, ServerApiVersion } = require(‘mongodb’);
// Functions
const proccessForm = async function (type, body) {};
//Global vars
const uri =
‘mongodb+srv://:@omar-db.pbwn3ml.mongodb.net/?retryWrites=true&w=majority’; //for mongodb
const mainFnPath = ‘/.netlify/functions/helpPP-webservice/’;
const dbName = ‘omar-db’;
const colName = ‘helpPP-DB’;
// MongoDB setup
// 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,
},
});
//
//
exports.handler = async function (event, context) {
const path = event.path; //the called path
//Setting up mongoDB
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Send a ping to confirm a successful connection
await client.db(dbName).command({ ping: 1 });
console.log(
‘Pinged your deployment. You successfully connected to MongoDB!’
);
//Reading the returned html
const db = client.db(dbName);
const col = db.collection(colName);
//Form handle:
if (path == mainFnPath + 'add') {
//Checking the method
// if (event.httpMethod == 'GET') {
// return {
// statusCode: 500,
// body: JSON.stringify({
// error: 'Form need POST request',
// }),
// };
// }
//Proccessing the form
proccessForm('add', event.body);
const query = {};
const projection = { returnhtml: 1 };
const data = await col.findOne(query, projection);
return {
statusCode: 200,
body: data.returnhtml,
headers: {
'Content-type': 'text/html',
},
};
}
} finally {
// Ensures that the client will close when you finish/error
console.log(‘You are no longer connected to MongoDB’);
await client.close();
}
return {
statusCode: 500,
body: ‘
ERROR! Cant show this page, please click the back button
’,headers: {
‘Content-type’: ‘text/html’,
},
};
};