博客
关于我
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/

你可能感兴趣的文章
node.js debug在webstrom工具
查看>>
Node.js Event emitter 详解( 示例代码 )
查看>>
Node.js GET、POST 请求是怎样的?
查看>>
Node.js HTTP模块详解:创建服务器、响应请求与客户端请求
查看>>
Node.js RESTful API如何使用?
查看>>
node.js url模块
查看>>
Node.js Web 模块的各种用法和常见场景
查看>>
Node.js 之 log4js 完全讲解
查看>>
Node.js 函数是什么样的?
查看>>
Node.js 函数计算如何突破启动瓶颈,优化启动速度
查看>>
Node.js 切近实战(七) 之Excel在线(文件&文件组)
查看>>
node.js 初体验
查看>>
Node.js 历史
查看>>
Node.js 回调函数的原理、使用方法
查看>>
Node.js 在个推的微服务实践:基于容器的一站式命令行工具链
查看>>
Node.js 实现类似于.php,.jsp的服务器页面技术,自动路由
查看>>
Node.js 异步模式浅析
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
Node.js 模块系统的原理、使用方式和一些常见的应用场景
查看>>