小程序和Vue Axios一直是從本地拿的假數據,很沒有逼格,今天把前後端搭了起來。直接從服務器拿數據,雖然也是假數據
前端代碼入戲
function sendAjax(url){
return new Promise(resolve => {
let xhr =new XMLHttpRequest()
xhr.open('GET',url)
xhr.onreadystatechange = function () {
if (xhr.status==200&&xhr.readyState==4){
console.log(xhr.responseText)
}
}
xhr.send()
})
}
async function asy(url) {
let res_1 = await sendAjax(url)
console.log(res_1)
}
asy('https://www.htmlstudio.top/')
這裏我用的是async函數,然後用Promise封裝的一個Ajax請求,沒學過ES6的同學看不懂沒有關係,我還有一個純原生JavaScript版本的。
原生Ajax請求代碼如下
let xhr =new XMLHttpRequest()
xhr.open('GET','https://www.htmlstudio.top/')
xhr.onreadystatechange = function () {
if (xhr.status==200&&xhr.readyState==4){
console.log(xhr.responseText)
}
}
xhr.send()
後端是用node寫的代碼
貼上如下
const http = require('http');
const fs = require('fs')
const hostname = '127.0.0.1';
const port = 8124;
http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "application/json",'Access-Control-Allow-Origin':'*'});
let res_1 = fs.readFileSync('res_1.json')
res.end(res_1)
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
監聽的是服務器的8124端口。
但是https的默認端口號衆所周知是443.
沒有關係,沒有關係。nginx反向代理代碼如下
server {
listen 443 ssl;
server_name www.htmlstudio.top;
ssl_certificate ssl/3490952_www.htmlstudio.top.pem;
ssl_certificate_key ssl/3490952_www.htmlstudio.top.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://127.0.0.1:8124;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
反向代理在nginx文件目錄中的conf目錄中。
last but not least。