node学习十九:从服务器主动发送请求(基于核心模块主动发送请求)

从服务器主动发送请求
http.request(options[, callback])

获取百度首页信息:

导入模块:

const http = require('http');
const path = require('path');
const fs = require('fs');

options 请求内容信息:

let options = {
    hostname : 'www.baidu.com',
    port : 80
}

发送请求http.request(options[, callback]):

let req = http.request(options,(res)=>{
    let info = '';

    res.on('data',(chunk)=>{
        info += chunk;
    });
    res.on('end',()=>{
        fs.writeFile(path.join(__dirname,'baidu.html'),info,(err)=>{
            console.log('已经获取到百度主页的内容');
        });
    });
});

表明请求的结束:

req.end();

测试后台接口(以前都是用的postman这个谷歌插件,模拟浏览器向服务器发送请求):

get请求:

导入模块:

const http = require('http');

options 请求内容信息:

let options = {
    protocol : 'http:',
    hostname : 'localhost',
    port : 3000,
    path : '/books'
}

发送请求http.request(options[, callback]):

let req = http.request(options,(res)=>{
    let info = '';

    res.on('data',(chunk)=>{
        info += chunk;
    });
    res.on('end',()=>{
        console.log(info);
    });
});

表明请求的结束:

req.end();

post请求:

导入模块:

const http = require('http');
const querystring = require('querystring');

options 请求内容信息:

let options = {
    protocol : 'http:',
    hostname : 'localhost',
    port : 3000,
    path : '/books/book',
    method : 'post',
    headers : {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
}

发送请求http.request(options[, callback]):

let req = http.request(options,(res)=>{
    let info = '';

    res.on('data',(chunk)=>{
        info += chunk;
    });
    res.on('end',()=>{
        console.log(info);
    });
});

将数据写入到请求主体:

let data = querystring.stringify({
    name : 'adafa',
    author : 'asdfa',
    category : 'afdasf',
    description : 'adsfa'
});
req.write(data);

表明请求的结束:

req.end();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值