创建node post接口请求 并返回Json

创建node post接口请求 并返回Json

req 请求对象,想知道req有哪些属性,可以查看 “http.request 属性整合”。

res 响应对象 ,收到请求后要做出的响应。想知道res有哪些属性,可以查看 “http.response属性整合”。

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'));

请求:

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

or node axios就不说了 说一下node 如下:

其中,options 参数是一个对象,包含了请求的一些基本参数,例如请求地址、端口、路径、请求方法、请求头等。

req 变量是一个请求实例,我们可以通过它来发起请求,并且通过该实例的 write 方法向服务器发送 POST 数据。

最后,我们调用 end 方法,表示数据发送完毕,请求被发起。

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();

最后是目录结构 直接node main 启动服务 node a 请求接口了 ~~·

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43867229/article/details/130590915