nodejs 实现从服务器发送请求
- nodejs 实现从服务器发送请求需要使用到 nodejs http 模块的
http.request(url[, options][, callback])方法。 http.request(url[, options][, callback])方法的重要属性:- url: url可以是一个字符串或url对象。
- options对象的重要属性
- protocol: 协议
- host :主机
- port :端口
- path :请求路径,应该包含查询字符串(如果有)
- method :请求方法
- headers :请求头,用于指定请求的类型如:
headers: { 'Content-Type': 'application/x-www-form-urlencoded', },
http.request()方法的url和options参数 可以根据需要选择使用其中一个,如果同时指定了url和options,则对象会被合并,其中options 属性优先。- callback 处理响应的回调函数,它有一个参数表示
response
http.request()返回http.ClientRequest类的实例。如果需要使用post等方法请求上传文件,则使用req.write();方法写入到ClientRequest对象。注意write()方法的参数要求是一个字符串。使用- 使用
http.request()时,必须始终调用req.end()来表示请求的结果,即使没有数据被写入到请求主体。 - 示例代码:
- 通过服务器发送请求第三方接口,获取天气。
const http = require('http'); // 第三方天气接口 let url = 'http://www.weather.com.cn/data/sk/101010100.html'; let req = http.request(url,function (res) { let info = ''; res.on('data',function (chunk) { info += chunk; }); res.on('end',function (err) { console.log(info); }); }); req.end(); - 通过服务器请求接口,添加书籍(注:请根据自己的需要修改options对象)
//============== 从服务器发送请求调用接口--添加图书 ================= const http = require('http'); const queryString = require('querystring'); let options = { protocol: 'http:', host: 'localhost', port: '3003', path: '/books/book', method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }; let req = http.request(options, function (res) { let info = ''; res.on('data', function (chunk) { info += chunk; }); res.on('end', function (err) { console.log(info); }); }); let data = queryString.stringify({ name: "《笑傲江湖》", author: "金庸", category: "文学", description: "一部武侠小说" }); req.write(data); req.end();
- 通过服务器发送请求第三方接口,获取天气。