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

你可能感兴趣的文章
Nginx模块 ngx_http_limit_req_module 限制请求速率
查看>>
nginx添加模块与https支持
查看>>
Nginx用户认证
查看>>
Nginx的location匹配规则的关键问题详解
查看>>
Nginx的Rewrite正则表达式,匹配非某单词
查看>>
Nginx的使用总结(一)
查看>>
Nginx的使用总结(三)
查看>>
Nginx的使用总结(二)
查看>>
Nginx的可视化神器nginx-gui的下载配置和使用
查看>>
Nginx的是什么?干什么用的?
查看>>
nginx看这一篇文章就够了
查看>>
Nginx简单介绍
查看>>
Nginx访问控制_登陆权限的控制(http_auth_basic_module)
查看>>
nginx负载均衡和反相代理的配置
查看>>
nginx负载均衡器处理session共享的几种方法(转)
查看>>
nginx负载均衡的5种策略(转载)
查看>>
nginx负载均衡的五种算法
查看>>
nginx转发端口时与导致websocket不生效
查看>>
Nginx运维与实战(二)-Https配置
查看>>
Nginx配置Https证书
查看>>