Home > OS >  POST API will not get save
POST API will not get save

Time:12-16

I did a POST request, and I got a signal via console.log, but my array doesn't get updated. What am I missing?

CLIENT:

const handleClick = () => {
    console.log("i was clicked")
    fetch("http://localhost:5000/", {
      method: "post",
      headers: {'Accept': 'application/json',"Content-Type": "application/json"},
      body: JSON.stringify(testPost),
    }).then((res) => res.json())
    .then(data =>{console.log("success", data)})
    .catch((err) =>{console.log("rejected", err)})
    
};

SERVER:

let data = {
  'skills': ["breathing ", "pooping"],
  'awards': 2  
}

app.get("/", (req, res) => {
  res.json(data);
});

app.post("/", (req, res) => {
   const {body} = req;
   res.json(data)
   console.log(body)
   console.log(data)
});

I use express, cors, body-parser on the server. On the client nothing special.

my expecation: { skills: [ 'breathing ', 'pooping', 'eating' ], awards: 2 } my results: { skills: [ 'breathing ', 'pooping' ], awards: 2 }

CodePudding user response:

First, I don't know what kind of data you send to your endpoint. So I think you send the whole object.

let data = {
  'skills': ["breathing ", "pooping"],
  'awards': 2  
}
// ...
app.post("/", (req, res) => {
  const {body} = req;

  data = body // this is what you are missing

  res.json(data)
  console.log(body)
  console.log(data)
});

CodePudding user response:

What you need is to update your data object on your post request. I am assuming from your comment that your request body is like this {skills: ["eating"]}. So you may update your post api like this.

let data = {
  'skills': ["breathing ", "pooping"],
  'awards': 2  
}

app.get("/", (req, res) => {
  res.json(data);
});

app.post("/", (req, res) => {
   // update skills array
   data.skills = [...data.skills, ...req.body.skills];
   res.json(data)
   console.log(body)
   console.log(data)
});

this should provide your expected result.

  • Related