简体   繁体   English

无法 POST - 我的 POST 请求有什么问题? 节点

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

I'm trying to learn node and have an issue with my POST request.我正在尝试学习 node 并且我的 POST 请求有问题。 I want to add a name and number to a list of contacts.我想将姓名和号码添加到联系人列表中。

Here is my post functionality这是我的帖子功能

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

Here is my hardcoded contacts as a reference这是我的硬编码联系人作为参考

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'
  }
];

I'm trying to add a我正在尝试添加一个

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

When doing sending the request I see this: Cannot POST /api/persons发送请求时,我看到:无法 POST /api/persons

With a random ID from a generateId function that I'm hoping works.使用来自我希望可以工作的 generateId 函数的随机 ID。

Thanks.谢谢。

POST /persons instead of POST /api/persons . POST /persons而不是POST /api/persons

Your route is app.post('/persons', , then you need to take a request with path is /persons .你的路线是app.post('/persons', ,那么你需要接受一个路径是/persons的请求。

If you want to create a route like POST /api/persons , let's change your route to app.post('/api/persons...如果你想创建一个像POST /api/persons这样的路由,让我们把你的路由app.post('/api/persons...

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

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