簡體   English   中英

無法 POST - 我的 POST 請求有什么問題? 節點

[英]cannot POST - What's wrong with my POST request? Nodejs

我正在嘗試學習 node 並且我的 POST 請求有問題。 我想將姓名和號碼添加到聯系人列表中。

這是我的帖子功能

// create
const generateId = () => {
  const personId = Math.random(...persons.map((p) => p.id));
  return personId;
};

app.post('/persons', (req, res) => {
  const body = req.body;

  if ((!body.name, !body.number)) {
    return res.status(400).json({
      error: 'content missing'
    });
  }
  const person = {
    name: body.name,
    number: body.number,
    id: generateId()
  };
  persons = persons.concat(person);

  res.json(person);
});

這是我的硬編碼聯系人作為參考

let persons = [
  {
    id: 1,
    name: 'Arto Hellas',
    number: '010-111111'
  },
  {
    id: 2,
    name: 'Ada Lovelace',
    number: '440-123456'
  },
  {
    id: 3,
    name: 'Dan Abramov',
    number: '330-349994'
  },
  {
    id: 4,
    name: 'Mary Poppendieck',
    number: '210-113578'
  }
];

我正在嘗試添加一個

{
    "name": "Bob",
    "Number": "12334"
}

發送請求時,我看到:無法 POST /api/persons

使用來自我希望可以工作的 generateId 函數的隨機 ID。

謝謝。

POST /persons而不是POST /api/persons

你的路線是app.post('/persons', ,那么你需要接受一個路徑是/persons的請求。

如果你想創建一個像POST /api/persons這樣的路由,讓我們把你的路由app.post('/api/persons...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM