简单记录下网站首页的搭建过程。html
自从网站域名备案成功下来,一直以来都没想好首页应该怎么写。其实不是没想好,而是没有准备好首页的多张大背景图片应该存放在那,毕竟是最廉价的云服务器,应该本着勤俭持家的理念,能省就省嘛。不过还好,bing中文搜索官网的背景图片天天都会更新,因而萌生出了用nodejs爬别人图片的方法~node
首先,须要给服务器安装nodejs,centOS下经过yum install nodejs
方式安装的nodejs是0.10版本的,根本没法写es6代码。没办法,只能经过源码安装了nginx
wget http://nodejs.org/dist/v4.5.0/node-v4.5.0.tar.gz tar -zxvf node-v4.5.0.tar.gz cd node-v4.5.0 ./configure make make install
ps:过程当中若是报找不到g++编译器,则请先安装g++yum install gcc-c++
输入node -v
检验是否安装成功
这里再顺便提一下安装npm的方法吧:
curl https://npmjs.com/install.sh | sudo sh
输入npm -v
检验是否安装成功c++
咳咳,接下来讲到重点了,准备爬cn.bing.com网站的背景图片。git
进入bing中文网址,cmd+alt+i
打开开发者工具选项,Network选项,cmd+r
刷新网页,找到网站的背景图片Ajax选项,这就是咱们要找的Ajax请求url
返回的结果以下所示
es6
github上有不少开源的nodeje抓包库,如superagent
而此次我所使用的是nodejs原生api
http.get(url, (res)=>{})
: get请求
https.get(url, (res)=>{})
: https方式
ps: 其实上面两种都是http(s).request(options, (res)=>{})
的GET方式简化版,只是由于当前大部分网站都是GET请求方式。
经过上面的图片,咱们此处使用http.get()
:github
const http = require('http'); const ajaxUrl = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'; http.get(ajaxUrl, (res) => { res.on('data', (d) => { console.log(d) }) })
此处终端的打印出来的是buffer对象,因此咱们须要将其转为字符串,而后转为json对象取到须要的图片url,代码以下:ajax
const json = JSON.parse(d.toString()); const src = json.images[0].url;
上面中的src就是咱们须要的图片url地址。npm
经过以上方式,虽然咱们获取到了目标图片的url,但如何把它应用到首页仍是个问题。
本人采起的方法是经过nodejs启动一个服务,返回目标字符串background-image:url(' + src + ')
,首页经过ajax请求以后添加到body的style对象上。
查看效果:https://qingguoing.com:3000
等等,有个坑,首页是经过nginx跑在80端口,而nodejs服务是跑在3000端口,因而就涉及到ajax跨域的问题。解决方法也很简单,nodejs设置返回头Access-Control-Allow-Origin: *
。因此nodejs最终代码以下所示:json
const https = require('https'); const http = require('http'); const fs = require('fs'); const options = { key: fs.readFileSync('./ssl/privkey1.pem'), cert: fs.readFileSync('./ssl/fullchain1.pem') }; const ajaxUrl = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'; https.createServer(options, function(request, response) { response.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': 'https://qingguoing.com' }); http.get(ajaxUrl, (res) => { res.on('data', (d) => { const json = JSON.parse(d.toString()); const url = json.images[0].url; response.write('background-image:url('+ url +')'); response.end(); }) }) }).listen(3000); console.log('server is listening on the port 3000');
ps1: 我的网站采用的是https连接,ssl证书是经过letsencrypt免费生成。
ps2: ajax跨域头只设置了我的网站的首页,因此你们若是想按我这种穷屌丝方式爬去图片,仍是去爬微软大厂的吧。既然都看到这了,相信对您来讲,这些都是小菜一碟
最后固然就是运行node程序了。不过若是你像我同样,经过终端命令远程链接到服务器端,那么你应该按照以下方式执行node命令:
node app.js&
此时开启的服务是后台跑起的,直接退出并不会终止已跑起的node程序