Node.js GET-POST请求


Node.js是一个基于Chrome V8引擎的JavaScript运行环境。Node.js包含许多内置模块,可以轻松地实现网络应用程序。本文将介绍Node.js中如何发送和处理GET和POST请求。

GET请求

GET是HTTP协议中的一种请求方法,可以用于从服务器获取数据。Node.js提供了http模块,可以使用该模块发送GET请求。

const http = require('http');

http.get('http://www.example.com', (res) => {
  console.log(`响应状态码: ${res.statusCode}`);
  console.log('响应头: ', res.headers);

  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`响应主体: ${chunk}`);
  });
}).on('error', (e) => {
  console.error(`请求遇到问题: ${e.message}`);
});

在上面的代码中,首先导入了Node.js的http模块,然后使用http.get方法向http://www.example.com发出GET请求。然后,在发出请求后,我们将通过一个回调函数来处理响应。这个回调函数的参数res是响应对象,我们可以使用这个对象来访问响应的元数据,比如状态码和响应头。然后我们使用res.setEncoding(‘utf8’)设置响应的编码方式,然后通过res.on(‘data’)监听响应主体中的数据。

POST请求

POST是HTTP协议中的另一种请求方法,适用于向服务器提交数据。Node.js中的http模块同样可以用于发送POST请求。

const http = require('http');

const data = JSON.stringify({
  name: 'John Doe',
  email: 'johndoe@example.com'
});

const options = {
  hostname: 'httpbin.org',
  path: '/post',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = http.request(options, (res) => {
  console.log(`响应状态码: ${res.statusCode}`);
  console.log('响应头: ', res.headers);

  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`响应主体: ${chunk}`);
  });
});

req.on('error', (error) => {
  console.error(`请求遇到问题: ${error}`);
});

req.write(data);
req.end();

在上面的代码中,我们首先将要发送的数据转换为JSON格式的字符串。然后,我们创建一个选项对象,该对象包含了将要发送的请求的元数据,包括HTTP方法、请求路径、请求头和请求主体数据的长度。然后,我们使用http.request方法创建一个http请求对象,并将选项对象传递给该方法。在创建请求对象后,我们通过req.write方法向请求主体中写入数据,并通过req.end方法发送请求。

处理请求

在服务器中处理GET和POST请求同样可以使用Node.js的http模块来实现。

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/test') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World!\n');
  } else if (req.method === 'POST' && req.url === '/test') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      console.log(body);
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('ok');
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found\n');
  }
});

server.listen(8080, () => {
  console.log('服务器已经启动:http://127.0.0.1:8080');
});

在上面的代码中,我们首先使用http.createServer方法创建一个服务器。在服务器上,我们通过req.method来判断请求的方法类型,以确定如何处理该请求。如果请求是GET方法并且请求路径是/test,服务器将以纯文本的形式响应一个“Hello World!”的消息。如果请求是POST方法并且请求路径是/test,服务器将读取请求主体中的数据,并将其显示在控制台上,然后以纯文本的形式响应一个“ok”的消息。否则,服务器将以404错误响应请求。最后,我们使用server.listen方法绑定端口并启动该服务器。