Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过URL访问和更新内存中的数据_Javascript_Node.js_Rest_Express_Http - Fatal编程技术网

Javascript 通过URL访问和更新内存中的数据

Javascript 通过URL访问和更新内存中的数据,javascript,node.js,rest,express,http,Javascript,Node.js,Rest,Express,Http,我目前正在学习如何使用node.js framework Express创建服务器 使用下面的代码,我了解如何访问或获取学生列表或按姓名获取1名学生,但是我不确定如何按id删除学生。我尝试了localhost:4000/students/1,但它不起作用,它的URL应该是什么样子 app.put方法也有同样的问题。如果我键入localhost:4000/students/James/art/50,我只会得到一个错误,说“无法获取localhost:4000/students/James/art/

我目前正在学习如何使用node.js framework Express创建服务器

使用下面的代码,我了解如何访问或获取学生列表或按姓名获取1名学生,但是我不确定如何按id删除学生。我尝试了localhost:4000/students/1,但它不起作用,它的URL应该是什么样子

app.put方法也有同样的问题。如果我键入localhost:4000/students/James/art/50,我只会得到一个错误,说“无法获取localhost:4000/students/James/art/50”,因此它实际上从未使用put方法

const express = require('express');
const bodyParser = require('body-parser');

app.use(bodyParser.json());

let students = [
  {
    id: 1,
    name: 'James',
    classes: {
      computer: 95,
      art: 92
    }
  },
  {
    id: 2,
    name: 'Leeroy',
    classes: {
      computer: 95,
      art: 92
    }
  }
];

app.get('/students', (req, res) => {
  res.json(students);
});

app.get('/students/:name', (req, res) => {
  res.json(students.find((student) => student.name === req.params.name));
});

app.put('/students/:name/:class/:grade', (req, res) => {
  const student = students.find((student) => student.name === req.params.name);

  if (student) {
    student.classes[req.params.class] = parseInt(req.params.grade);
    res.status(201).send(`Student ${req.params.name} was assigned a grade of ${req.params.grade} in ${req.params.class}`);
  } else {
    res.status(404).send('Student not foun');
  }
});

app.delete('/students/:id', (req, res) => {
  const student = students.find((student) => student.id === req.params.id);

  if (student) {
    students = students.filter((obj) => obj.id !== req.params.id);
    res.status(201).send('Student was deleted.');
  }
});

app.listen(4000, () => {
  console.log('Your app is listening on port 4000');
});

您需要使用一个工具来测试不同的请求,我建议您可以在那里测试DELETE、PUT和POST请求