Hello dear netlify community,
when I make a lambda function connection and connect my application to mongoose, I get the error
Here is my toml file
[build]
functions=“/functions”
[[redirects]]
from=“/api/*”
to=“/.netlify/functions/:splat”
status=200
force = true
headers = {X-From = “Netlify”}
[[headers]]
Define which paths this specific [[headers]] block will cover.
for = “/"
[headers.values]
Access-Control-Allow-Origin = "”
Here is the request:
const mongoose = require(‘mongoose’)
const User = require(‘…/server/models/user’)
await mongoose.connect(${process.env.MONGO_URI}
, {
useNewUrlParser: true,
useUnifiedTopology: true
}
);
exports.handler = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
try{
const user = await User.findOne({
email: 'bbbb'
})
if(!user) {
await User.create({
name: 'kkk',
email: 'llll',
verified: true,
})
}
return {
statusCode: 200,
status:"ok",
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "X-Token, append,delete,entries,foreach,get,has,keys,set,values,Authorization",
"Content-Type":"application/json"
}
}
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message })
};
}
}
In the frontend, I invoke the function like so:
async function loginUser(e) {
e.preventDefault()
try{
const response = await fetch(${process.env.REACT_APP_NETLIFY_URL}.netlify/functions/addtask
, {
method: ‘POST’,
mode: ‘cors’,
statusCode: 200,
status:“ok”,
headers: {
‘Content-Type’: ‘application/json’,
‘Accept’: ‘application/json’,
“Access-Control-Allow-Origin”: “*”,
“Access-Control-Allow-Methods”: “DELETE, POST, GET, OPTIONS”,
“Access-Control-Allow-Headers”: “Origin, X-Token, append,delete,entries,foreach,get,has,keys,set,values,Authorization”,
},
body: JSON.stringify({
/////
})
})
} catch (err){
console.log(err, ‘err here’)
}
}
Here is my github repo https://github.com/Datex-P/flashcard-react-stable/ and here the deployed app https://master–cool-gnome-d84e5e.netlify.app/login. Thanks so much for helping me and everyone with this problem out!