/** eslint-disable */
var http = require('http'),httpProxy = require('http-proxy'),HttpProxyRules = require('http-proxy-rules');// Set up proxy rules instance
var port = 9090
var proxyRules = new HttpProxyRules({rules: {'/api/(.*)': 'https://baidu.com/$1', // 測試環境游戲服務},default: 'https://baidu.com', // default target
});// Create reverse proxy instance
var proxy = httpProxy.createProxy({ autoRewrite: true, changeOrigin: true });// Create http server that leverages reverse proxy instance
// and proxy rules to proxy requests to different targets
http.createServer(function (req, res) {// a match method is exposed on the proxy rules instance// to test a request to see if it matches against one of the specified rulesvar target = proxyRules.match(req);console.info({ target });if (target) {// 設置跨域頭res.setHeader('Access-Control-Allow-Origin', 'http://localhost:7456');res.setHeader('Access-Control-Allow-Credentials', 'true');res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, App-Info, X-Device, Session');// 檢查請求是否為預檢請求if (req.method === 'OPTIONS') {// 返回 HTTP OK 狀態碼(200)以滿足預檢請求的要求res.writeHead(200);res.end();return;}return proxy.web(req, res, {target: target,});}res.writeHead(500, { 'Content-Type': 'text/plain' });res.end('The request url and path did not match any of the listed rules!');}).listen(port);console.info('======proxy on localhost: ' +port + '======');
console.info('===proxy table===');
console.info({rules: {'/api/(.*)': 'https://baidu.com/$1', // 測試環境游戲服務},default: 'https://baidu.com', // default target
});
用后端給的接口前綴來代替代碼中的?::::::? ? ?https://baidu.com?
即可監聽本地的http://localhost:7456/? ?中帶api關鍵字的訪問,反向代理到后端服務器
原理是:
- ? ?前端和后端不在同一個服務器域名下,會造成跨域阻攔。
- ? 后端和后端的訪問不管是不是同源環境,是不是一個域名下,都不會有跨域阻攔。
- ? node.js起一個簡單的后端服務,將前端對后端的跨域訪問,先通過node服務和本地前端都是本地的同源關系正常訪問node服務,node反向代理到跨域的后端服務上成服務器之間的訪問。
? ? ?解決辦法常用的就是如上,還可以找后端將服務器改為不阻止跨域,后端沒安全感,一般不干。
?