简体   繁体   中英

POST API will not get save

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 }

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)
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM