简体   繁体   English

POST API 不会保存

[英]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.我做了一个 POST 请求,我通过 console.log 收到了一个信号,但我的数组没有得到更新。 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.我在服务器上使用expresscorsbody-parser On the client nothing special.在客户端没什么特别的。

my expecation: { skills: [ 'breathing ', 'pooping', 'eating' ], awards: 2 } my results: { skills: [ 'breathing ', 'pooping' ], awards: 2 }我的期望:{ skills: [ 'breathing', 'pooping', 'eating'], awards: 2 } 我的结果:{ 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"]} .我从您的评论中假设您的请求正文是这样的{skills: ["eating"]} So you may update your post api like this.所以你可以像这样更新你的post api。

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.这应该提供您的预期结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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