1.在前后端分离的解决方案中,本文介绍的一种方式,,
NodeJs作为前端服务器,其实只是远程服务器的代理,Node收到请求后,访问远程接口,将返回的数据返回给前端
安装NodeJs的部分这里不再累述,分离操作如下:
2.前端服务器文件testProxy.js
var http=require("http");
var url=require("url");
var fs=require('fs');
//var querystring = require('querystring');
var server=http.createServer(function(sreq,sres){
var url_parts=url.parse(sreq.url);//解析路径
var pathname = url_parts.pathname;
//node路径下的请求不转发
console.log("-----文件路径-------"+pathname);
if(pathname.match(/^\/node/)!=null){
console.log("静态文件");
var realPath = 'c:/Users/jh/Desktop'+pathname;//前台的html需放到我的桌面下c:/Users/jh/Desktop
fs.exists(realPath, function (exists) {
if (!exists) {
sres.writeHead(404, {'Content-Type': 'text/plain'});
sres.write("404 not found.");
sres.end(data,'utf-8');
} else {
fs.readFile(realPath, "binary", function (err, file) {
if (err) {
sres.writeHead(500, {'Content-Type': 'text/plain'});
sres.end(err);
} else {
sres.writeHead(200, {'Content-Type': 'text/html'});
sres.write(file, "binary");
sres.end();
}
});
}
});
}else{
console.log("url_name----------"+url_parts.pathname)
var options = {
host: 'localhost', //跨域地址,我访问的是本机
port: '8888',
path: url_parts.pathname
};
// 处理响应的回调函数
var callback = function(response){
// 不断更新数据
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// 数据接收完成
console.log(body);
sres.write(body);
sres.end();
});
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();
}
});
server.listen(3000,"127.0.0.1", function () {//监听端口8080
console.log("开始监听"+server.address().port+"......");
});
3.静态页面test.html ,注意,testProxy.js中指定静态文件位置
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("hello world");
$.get("http://localhost:3000/name",function(data,status){
alert("数据: " + data + "\n状态: " + status);
$("#test3").val(data);
});
});
});
</script>
</head>
<body>
<button>HTTP GET</button>
<input type="text" id="test3" value="hello world"></p>
</body>
</html>
4.启动Node node testProxy.js
5.访问 http://localhost:3000/node/test.html
这里写图片描述
6.后台接口返回test
7.点击按钮,返回后台数据