'How do I send data to express backend from html frontend without a form?
I am trying to create a small ecommerce website where I need to have a cart page. I need to make it so when a user clicks on Add to cart button, the particular item will get sent to the backend and stored in the cart collection.
What I'm having trouble with is that when I click the add to card button and the function linked to it runs, I get an error stating : SyntaxError: Unexpected token " in JSON at position 0
Here's my function which is supposed to send data to the backend:
let addToCart = async (item) => {
// item is the object I get which contains all the information I need
try {
let product = item._id;
await fetch('http://localhost:5000/cart', {
method: 'post',
body: product,
headers: {
'Content-Type': 'application/json',
},
});
} catch (e) {
console.log({error : e});
}
};
This is my cart model :
const cartSchema = new mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
required: true,
},
cartProducts: {
type: Array
},
},
{
versionKey: false,
timestamps: true,
}
);
This is my cart controller POST CRUD
router.post('', authenticate, async (req, res) => {
const user = req.user;
console.log(user);`
try {
const cart = await Cart.findOneAndUpdate(
{ userId: user._id },
{
$push: {
cartProducts: req.body,
},
},
{ new: true, upsert: true }
);
return res.status(200).send(cart);
} catch (err) {
return res.status(400).send({ message: err.message });
}
});
I am able to get user using authenticate middleware. I can post everything using Postman but I can't figure how to get rid of the Syntax error.
When I console.log typeof item, I get an object. Product's type is string. I have also tried using JSON.stringify but nothing seems to be working. I have also tried using bodyparser middleware.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
