最近工作任务中设计到了补数据,需要往本地服务发请求。使用浏览器发送会有跨域问题,所以就是用到了node的request模块进行发送,总结学习到的一些东西做一下记录。
遇到的坑,主要是本地安装request等模块时,执行npm install request --save
有时候会提示你缺少xxx模块,直接将node_modules删了重新安装,就没那么多毛病了。
node环境没有浏览器的"域",所以也就没有跨域这个概念了。
request(options, callback)
The first argument can be either a url
or an options
object. The only required option is uri
; all others are optional.
说的很明白,只有字符串url是必须要写的,其他参数都是optional。
参照前端的请求模式,request可以发送普通的get,post,post json,表单,文件上传,新建cookie并发送请求等
具体配置也很容易就是github上查就行了(https://github.com/request/request)
request({
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: {
name: 'lyadon'
}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
大概发送一个post请求就是这样的,json: true 这个设置可以自动将body请求对象进行字符串转换 JSON.stringify(),保证后端得到的是json字符串。
request模块是采用回调的方式,也可以使用promise的模式,具体参展(https://github.com/request/request-promise)
npm install --save request
npm install --save request-promise
var rp = require('request-promise');
rp('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});
需要安装request-promise模块,也要安装request,然后就可以使用promise的方式而不是回调了。
配置也简单,查看github上就行了。(https://github.com/request/request-promise)