Home  >  Article  >  Web Front-end  >  nodejs writing delete interface

nodejs writing delete interface

WBOY
WBOYOriginal
2023-05-28 09:37:06581browse

Node.js is an open source, cross-platform JavaScript runtime environment that is widely used in web application development. One of the features is the ability to use the HTTP module to create servers and handle HTTP requests. In actual development, we not only need to create an HTTP server, but also need to implement various RESTful API interfaces. This article will introduce how to implement a delete interface in Node.js.

  1. Create HTTP server

First, we need to use the http module of Node.js to create an HTTP server, the code is as follows:

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World
');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

The above code creates Create an HTTP server and listen on port 3000. When we access http://localhost:3000/, the server will return "Hello World".

  1. Implementing the deletion interface

Next, we need to implement a deletion interface. In RESTful APIs, deletion operations usually use the HTTP DELETE method. We can use the request event of the Node.js HTTP module to listen for client requests.

First, we need to define a URL to delete the interface. Taking the example as an example, we assume that we want to delete a user whose URL is http://localhost:3000/users/:id, where :id is the user's unique identifier. We can use the url module of Node.js to parse the URL into an object and then obtain the :id parameter. The code is as follows:

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
  const reqUrl = url.parse(req.url, true);
  const id = reqUrl.pathname.split('/')[2];

  if (req.method === 'DELETE' && reqUrl.pathname === `/users/${id}`) {
    // 处理删除请求
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

In the above code, we first use the url.parse method to parse the requested URL into an object, and then use the split method to obtain the :id parameter.

Next, we determine whether the requested method is DELETE and the URL contains the /id parameter. If so, it means that the client is requesting the interface to delete the user. We can implement deletion logic in if statements.

  1. Implement deletion logic

In the deletion logic, we need to use the fs module of Node.js to read user data and rewrite the deleted data into the file middle. Assume that user data is stored in a users.json file with the following content:

{
  "1": {
    "name": "张三",
    "age": 20,
    "email": "zhangsan@example.com"
  },
  "2": {
    "name": "李四",
    "age": 30,
    "email": "lisi@example.com"
  },
  "3": {
    "name": "王五",
    "age": 25,
    "email": "wangwu@example.com"
  }
}

We can first use the readFileSync method of the fs module to read the contents of the users.json file and then parse it into a JavaScript object .

Next, we can use JavaScript’s delete operator to delete the user object to be deleted from the JavaScript object. Finally, we use the fs module's writeFileSync method to rewrite the modified JavaScript object into the users.json file. The code is as follows:

const http = require('http');
const url = require('url');
const fs = require('fs');

const server = http.createServer((req, res) => {
  const reqUrl = url.parse(req.url, true);
  const id = reqUrl.pathname.split('/')[2];

  if (req.method === 'DELETE' && reqUrl.pathname === `/users/${id}`) {
    // 读取用户数据
    const users = JSON.parse(fs.readFileSync('./users.json'));

    // 删除用户
    delete users[id];

    // 写入修改后的用户数据
    fs.writeFileSync('./users.json', JSON.stringify(users));

    // 返回删除成功提示
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end(`User ${id} deleted successfully`);
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

In the above code, we first use the readFileSync method of the fs module to read the content in the users.json file and parse it into a JavaScript object. Then, we use the delete operator to remove the user to be deleted from the JavaScript object. Finally, we use the writeFileSync method of the fs module to rewrite the modified JavaScript object into the users.json file and return a successful deletion prompt.

  1. Test deletion interface

Now, we have completed the implementation of the deletion interface. In order to test whether the interface is working properly, we can use the curl command to simulate an HTTP DELETE request. The code is as follows:

curl -X DELETE http://localhost:3000/users/1

The above command will send an HTTP DELETE request to http://localhost:3000/users/1 to delete the user with ID 1 from the users.json file. If everything is normal, the server will return the "User 1 deleted successfully" prompt.

Summary

This article introduces how to implement a delete interface in Node.js. We use the http module of Node.js to create an HTTP server and use the request event to listen for client requests. When the client sends an HTTP DELETE request, we use the fs module to read the user data and use the JavaScript delete operator to delete the user to be deleted from the JavaScript object. Finally, we use the fs module to re-write the modified JavaScript object into the user data file.

The above is the detailed content of nodejs writing delete interface. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn