1、本段代碼用於解決前后端分離過程中產生的跨域問題。原理上是使用代理轉發。使用nodejs語法編寫,需要運行在nodejs環境下。
2、使用方法
1、普通ajax請求的url需要改成代碼中監聽的路由和端口。
2、需要在ajax請求中添加額外添加2個參數,一,baseUrl真實訪問接口的host地址;二,pathUrl需要訪問的接口的path地址。
const url = require('url');
const http = require('http');
const https = require('https'); // cnode是https協議
//導入querystring模塊(解析post請求數據)
var querystring = require('querystring');
const server = http.createServer((req, res) => {
//var params = req.url.toString(1, req.url.length);
//var params = url.parse(req.url, true).query;
var data = '';
if (req.method == "GET") {
data = url.parse(req.url, true).query;
data = JSON.stringify(data);
let opt = {
hostname: '',
method: req.method,
path: '',
headers: {
"Content-Type": 'application/json',
"Content-Length": data.length
}
}
if(data){
opt.hostname = JSON.parse(data).baseUrl;
opt.path = JSON.parse(data).pathUrl;
}
let body = '';
let breq = https.request(opt, function (bres) {
bres.on('data', function (data) {
body += data;
}).on('end', function () {
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,X-URL-PATH,x-access-token"
})
res.end(body);
});
}).on('error', function (e) {
console.log("error: " + e.message);
})
breq.write(data);
breq.end();
} else {
req.on('data',function(r){
data += r;
})
req.on('end', function () {
var opt = {
hostname: '',
method: req.method,
path: '',
headers: {
"Content-Type": 'application/json',
"Content-Length": data.length
}
}
if(data){
opt.hostname = JSON.parse(data).baseUrl;
opt.path = JSON.parse(data).pathUrl;
}
let body = '';
let breq = https.request(opt, function (bres) {
bres.on('data', function (data) {
body += data;
}).on('end', function () {
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,X-URL-PATH,x-access-token"
})
res.end(body);
});
}).on('error', function (e) {
console.log("error: " + e.message);
})
breq.write(data);
breq.end();
})
}
}).listen(3000, '127.0.0.1');
console.log('監聽 127.0.0.1:3000,服務已啟動');
