node本地安装位置: C:\Program Files (x86)\nodejs
相关网址:https://www.cnblogs.com/woodk/p/5817755.html
代理服务器搭建
cmd:
cd 项目目录
cnpm install http-proxy --save-dev
npm init // 创建项目
node proxy.js // 进入项目目录 - cmd 启动项目
npm init
项目启动效果:
接口跨域 访问失败:
404解决办法:
请求是404问题解决啦:
pathname.indexOf("mspj-mall-admin");这段代码的问题
'mspj-mall-admin' 是请求接口某个固定字段
如接口 /api/sysUnit/list
就可以写成 pathname.indexOf("api");
代码整理如下:
node系统结构:
proxy.js: 启动文件配置
var PORT = 3000;
var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({
target: 'http://172.18.19.24:8080/', //接口地址
changeOrigin: true,
// 下面的设置用于https
// ssl: {
// key: fs.readFileSync('server_decrypt.key', 'utf8'),
// cert: fs.readFileSync('server.crt', 'utf8')
// },
// secure: false
});
proxy.on('error', function(err, req, res){
res.writeHead(500, {
'content-type': 'text/plain'
});
console.log(err);
res.end('Something went wrong. And we are reporting a custom error message.');
});
var server = http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
//var realPath = path.join("main-pages", pathname); // 指定根目录
var realPath = path.join("./", pathname);
console.log(pathname);
console.log(realPath);
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
//判断如果是接口访问,则通过proxy转发
if(pathname.indexOf("hiiap") > 0){
proxy.web(request, response);
return;
}
fs.exists(realPath, function (exists) {
if (!exists) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.write("This request URL " + pathname + " was not found on this server.");
response.end();
} else {
fs.readFile(realPath, "binary", function (err, file) {
if (err) {
response.writeHead(500, {
'Content-Type': 'text/plain'
});
response.end(err);
} else {
var contentType = mine[ext] || "text/plain";
response.writeHead(200, {
'Content-Type': contentType
});
response.write(file, "binary");
response.end();
}
});
}
});
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
<META HTTP-EQUIV="expires" CONTENT="0">
<title>投行业务管理系统</title>
</head>
<body>
<h3>node 代理服務器</h3>
<ul>
<li></li>
</ul>
<script src="../js/jquery-1.8.2.min.js"></script>
<script>
$(function(){
getRecommendProducts()
})
function getRecommendProducts(){
$.ajax({
url : "/hiiap/product/getRecommendProducts",
type : "post",
data : 'json',
success : function(data) {
console.log(data)
},
error : function(){ console.log('请求后台失败!') }
})
}
</script>
</body>
</html>
效果图如下所示: