Create node post interface request and return Json

Create node post interface request and return Json

req request object. If you want to know what attributes req has, you can check "http.request attribute integration".

res response object, the response to be made after receiving the request. If you want to know what attributes res has, you can check "http.response attribute integration".

const http = require('http');

const server = http.createServer((req, res) => {
    
    
  if (req.method === 'POST' && req.url === '/api/data') {
    
    
    let data = '';

    req.on('data', (chunk) => {
    
    
      data += chunk;
    });

    req.on('end', () => {
    
    
      try {
    
    
        const json = JSON.parse(data);
        // 在这里可以对接收到的数据进行处理
        const response = {
    
    
          success: true,
          message: '数据已收到',
          data: json
        };
        res.writeHead(200, {
    
     'Content-Type': 'application/json' });
        res.end(JSON.stringify(response));
      } catch (error) {
    
    
        res.writeHead(400, {
    
     'Content-Type': 'application/json' });
        res.end(JSON.stringify({
    
     success: false, message: '无效的JSON数据' }));
      }
    });
  } else {
    
    
    res.writeHead(404, {
    
     'Content-Type': 'application/json' });
    res.end(JSON.stringify({
    
     success: false, message: '无效的请求' }));
  }
});

server.listen(3000, () => console.log('服务器已启动,端口号:3000'));

ask:

const axios = require('axios');

const postData = {
    
    key: 'value'};

axios.post('http://localhost:3000/api/data', postData)
  .then((response) => {
    
    
    console.log(response.data);
  })
  .catch((error) => {
    
    
    // console.error(error);
  });

I won’t talk about node axios or node axios. Let’s talk about node as follows:

Among them, the options parameter is an object that contains some basic parameters of the request, such as request address, port, path, request method, request header, etc.

The req variable is a request instance through which we can initiate a request and send POST data to the server through the write method of the instance.

Finally, we call the end method, indicating that the data is sent and the request is initiated.

const http = require('http');

const postData = JSON.stringify({
    
    key: 'value'});

const options = {
    
    
  hostname: 'localhost',
  port: 3000,
  path: '/api/data',
  method: 'POST',
  headers: {
    
    
    'Content-Type': 'application/json',
    'Content-Length': postData.length
  }
};

const req = http.request(options, (res) => {
    
    
  let data = '';

  res.on('data', (chunk) => {
    
    
    data += chunk;
  });

  res.on('end', () => {
    
    
    console.log(JSON.parse(data));
  });
});

req.on('error', (error) => {
    
    
  console.error(error);
});

req.write(postData);
req.end();

The last is the directory structure. Directly node main starts the service node a and requests the interface ~~·

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43867229/article/details/130590915