Hey everyone,
I'm currently facing an issue and could really use some assistance. I'm working on a project where I need to send data from the frontend to MongoDB. To achieve this, I understand that I need to make a POST request, but I'm unsure about the options available to me. Specifically, I'm wondering if there is anything provided by PayloadCMS for this purpose. I've also tried using the LocalAPI, but it doesn't seem to be functioning correctly in my case.
If any of you have experience with this or can provide guidance, I would greatly appreciate it. I'm specifically looking for a solution that allows me to send data from the frontend to MongoDB effectively. Any insights, code snippets, or recommended resources would be incredibly helpful.
Hi, wouldn't it be better to send the request from the frontend directly to payload? You can connect payloadcms to mongodb and it will make it easier for you to manage the data in your database
Here's an example of an axios request you can make from your front-end to payloadcms
// Create an object with the data to be sent in the POST request
const data = {
name: 'John Doe',
age: 25,
email: 'johndoe@example.com'
};
// Make a POST request to a specific URL with the data
axios.post('https://your-backend-url/api/users', data)
.then(response => {
console.log('Response:', response.data);
// Handle the response data here
})
.catch(error => {
console.error('Error:', error.message);
// Handle any errors that occurred during the request
});
https://payloadcms.com/docs/rest-api/overview
You can find the docs for the REST api here, I use the docs a lot, they are really helpful
I just found out that on the payloadcms documentation they added examples on how to make requests to the api, here's what I found for the POST request, it uses the fetch function instead of using axios
try {
const req = await fetch('{cms-url}/api/{collection-slug}', {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "New page",
content: "Here is some content"
}),
})
const data = await req.json()
} catch (err) {
console.log(err)
}
Thank you, it works 😄
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.