博客
关于我
nodejs 发起 GET 请求示例和 POST 请求示例
阅读量:792 次
发布时间:2023-02-16

本文共 1738 字,大约阅读时间需要 5 分钟。

Node.js HTTP???????

?Node.js??http????????HTTP????????????HTTP??????????????????????API???????????????????http????GET?POST??????


GET????

?????????????URL??GET?????????

const http = require('http');const options = {    hostname: 'www.example.com',    port: 80,    path: '/path/to/resource',    method: 'GET'};const req = http.request(options, (res) => {    console.log(`???: ${res.statusCode}`);    console.log(`???: ${JSON.stringify(res.headers)}`);    res.setEncoding('utf8');    res.on('data', (chunk) => {        console.log(`????: ${chunk}`);    });    res.on('end', () => {        console.log('??????');    });});req.on('error', (error) => {    console.error(`??????: ${error.message}`);});req.end();

POST????

?????????????URL??POST???

const http = require('http');const querystring = require('querystring');const postData = querystring.stringify({    'key1': 'value1',    'key2': 'value2'});const options = {    hostname: 'www.example.com',    port: 80,    path: '/api/endpoint',    method: 'POST',    headers: {        'Content-Type': 'application/x-www-form-urlencoded',        'Content-Length': Buffer.byteLength(postData)    }};const req = http.request(options, (res) => {    console.log(`???: ${res.statusCode}`);    console.log(`???: ${JSON.stringify(res.headers)}`);    res.setEncoding('utf8');    res.on('data', (chunk) => {        console.log(`????: ${chunk}`);    });    res.on('end', () => {        console.log('POST????');    });});req.on('error', (error) => {    console.error(`??????: ${error.message}`);});req.write(postData);req.end();

????

  • ????????????????????????????????JSON??????????????????????????axios?node-fetch?????
  • ???????req.write()????????????????

?????????????????????????????HTTP???????????????????????

转载地址:http://gvjfk.baihongyu.com/

你可能感兴趣的文章
Netty常见组件二
查看>>
netty底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
查看>>
Netty心跳检测
查看>>
Netty心跳检测机制
查看>>
Netty核心模块组件
查看>>
Netty框架内的宝藏:ByteBuf
查看>>
Netty框架的服务端开发中创建EventLoopGroup对象时线程数量源码解析
查看>>
Netty源码—2.Reactor线程模型一
查看>>
Netty源码—3.Reactor线程模型三
查看>>
Netty源码—4.客户端接入流程一
查看>>
Netty源码—4.客户端接入流程二
查看>>
Netty源码—5.Pipeline和Handler一
查看>>
Netty源码—5.Pipeline和Handler二
查看>>
Netty源码—6.ByteBuf原理一
查看>>
Netty源码—6.ByteBuf原理二
查看>>
Netty源码—7.ByteBuf原理三
查看>>
Netty源码—7.ByteBuf原理四
查看>>
Netty源码—8.编解码原理一
查看>>
Netty源码—8.编解码原理二
查看>>
Netty源码解读
查看>>