本文共 1738 字,大约阅读时间需要 5 分钟。
?Node.js??http????????HTTP????????????HTTP??????????????????????API???????????????????http????GET?POST??????
?????????????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(); ?????????????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(); axios?node-fetch?????req.write()?????????????????????????????????????????????HTTP???????????????????????
转载地址:http://gvjfk.baihongyu.com/