博客
关于我
nodejs 发起 GET 请求示例和 POST 请求示例
阅读量:799 次
发布时间: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/

你可能感兴趣的文章
Objective-C实现Burrows-Wheeler 算法(附完整源码)
查看>>
Objective-C实现CaesarsCiphe凯撒密码算法(附完整源码)
查看>>
Objective-C实现calloc函数功能(附完整源码)
查看>>
Objective-C实现canny边缘检测算法(附完整源码)
查看>>
Objective-C实现cartesianProduct笛卡尔乘积算法(附完整源码)
查看>>
Objective-C实现check strong password检查密码强度算法(附完整源码)
查看>>
Objective-C实现chudnovsky algorithm楚德诺夫斯基算法(附完整源码)
查看>>
Objective-C实现CIC滤波器(附完整源码)
查看>>
Objective-C实现circle sort圆形排序算法(附完整源码)
查看>>
Objective-C实现CircularQueue循环队列算法(附完整源码)
查看>>
Objective-C实现clearBit清除位算法(附完整源码)
查看>>
Objective-C实现climbStairs爬楼梯问题算法(附完整源码)
查看>>
Objective-C实现cocktail shaker sort鸡尾酒排序算法(附完整源码)
查看>>
Objective-C实现cocktailShakerSort鸡尾酒排序算法(附完整源码)
查看>>
Objective-C实现CoinChange硬币兑换问题算法(附完整源码)
查看>>
Objective-C实现collatz sequence考拉兹序列算法(附完整源码)
查看>>
Objective-C实现Collatz 序列算法(附完整源码)
查看>>
Objective-C实现comb sort梳状排序算法(附完整源码)
查看>>
Objective-C实现combinationSum组合和算法(附完整源码)
查看>>
Objective-C实现combinations排列组合算法(附完整源码)
查看>>