I'm new to fetch and I'm trying to convert $ajax into fetch without await, async.. (I didn't make it till there). I'm using Express for the server.
The fundamental concept of fetch/promise is unclear for me and I don't know how can I send the parameter selected
in JSON format, and how to receive it from the server. I thought I would be ok to receive it (from server-side) with JSON.parse(req.body.data)
, and I tried several things with it but it keeps giving me errors both on client-side and server-side(errors are down below).
** I tried Fetch: POST json data from someone's feedback but sadly I couldn't make it work for me. **
Any help would be appreciated.
addProduct(selected) {
const orderList = this;
function post(){
// const data = {
// selected:"selected",
// }
fetch('/cart', {
method:'post',
headers:{
"Accept": "application/json, text/plain, */*",
"Content-type": "application/json; charset = UTF-8"
},
body: JSON.stringify(selected),
})
.then(res => {
res.json()
console.log(res)})
.then(res => console.log(res));
}
post();
}
server-side error: SyntaxError: Unexpected token u in JSON at position 0
client-side error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
(the following codes are the original $ajax code that works)
Client-side
menuItemClick(target) {
const selected = this.menuList.data.find(product => product.id == target.dataset.id)
const selectedIndex = this.orderList.data.findIndex(product => product.id == selected.id)
if (selectedIndex === -1) {
selected.count = 1;
this.orderList.addProduct(selected)
}
addProduct(selected) {
const orderList = this;
$.ajax({
url:"http://localhost:8080/cart",
type:"post",
dataType: "json",
data: {data:JSON.stringify(selected)},
success: function(orderedItem){
orderList.data.push(orderedItem),
orderList.orderRender()
}
})
}
Server-side
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.post("/cart", (req, res) => {
const bodyData = JSON.parse(req.body.data);
db.query(
`INSERT INTO cartData (prodId) VALUES(${bodyData.id})`,(err, rows) => {
db.query(
`SELECT cartData.id as orderId, prodName, price, category, count, menuData.Id as id FROM menuData JOIN cartData on menuData.id = cartData.prodId where prodId = ${bodyData.id}`,
(err, orderedItem) => {
res.send({"orderedItem": "${orderedItem[0]}"});
}
);
}
);
});