curl-request模块学习

文章参考

  1. https://github.com/request/request#custom-http-headers
  2. Request —— 让 Node.js http请求变得超简单

问题来源

学习nodejs 的CURL模块,这里引用了 require 模块

  1. 解决浏览器跨域
  2. 去爬网站的数据
  3. 分散业务逻辑处理——交给后台处理

将JSON对象转为get请求的参数

引用到了querystring模块

var querystring = require('querystring');
var contents = querystring.stringify({
	code: 'code777',
	grant_type: 'authorization_code',
	client_id: '2477984199333222',
	client_secret: '971a06012b81382350a26ae48c2ebe0d99002211',
	redirect_uri: '123456789'
});
console.log(contents);

结果: code=code777&grant_type=authorization_code&client_id=2477984199333222&client_secret=971a06012b81382350a26ae48c2ebe0d99002211&redirect_uri=123456789

request 请求

get获取数据

var request = require('request');
request('http://www.dsiowe.com?code=code777&grant_type=authorization_code', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // 打印google首页
  }
})

参数直接跟在URL地址后面

request设置header等更多配置信息

let request = require('request');
let requestData = '';
let url = 'https://dsalfjlkds.dsa/access_token?code=code777&grant_type=authorization_code&client_id=2477984199333222';

responsebody = request({
  url: url,
  method: "GET",
  json: true,
  headers: {
    "content-type": "application/json",
  },
  body: JSON.stringify(requestData)
}, function(error, response, body) {
  if (!error && response.statusCode == 200) {
	return body
  }
});

request.post 请求

var request = require('request');
request.post(
	{
		url:'http://hovertree.com:9095/phpTest.php',
		form:{
			username:'hahaha',
			password:'wowowowow'
		},
		encoding:'utf8'
	},
	function(error, response, body){
		if(response.statusCode == 200){
			console.log(body);
		}else{
			console.log(response.statusCode);
		}
	}
);

个人感觉request API 实现方式有点类似于 jquery的ajax方法

阅读更多

没有更多推荐了,返回首页