通过node.js进行前后端分离

       现在很多公司企业都是前后端分离开发,两端互相不干扰。由于以前在学校时习惯了把前端东西放在同一个项目里的projects目录或者springboot里的resources/static文件夹下,所以作为一个后端程序员,今天我也简单的介绍一下通过node.js进行前后端分离开发。

      首先,确定自己已经搭建好node和npm安装环境,最好的话安装一下cnpm会快很多。

其次,准备一个可以通过localhost:8080/api/users显示数据  访问假数据或者连接数据库。我推荐用srpingboot快速搭建一个。具体可以看我的源码,如果你不喜欢或者没用过springboot的话也可以用spring mvc搭建一个

(1)创建一个项目文件夹,文件夹名字是你的项目名在这里我就改为test-frontend。

(2)创建一个package.json。用cmd在test-frontend下运行npm init命令,一步一步填入你的项目相关信息。记得最后填yes才会生成。

(3) 用npm或者cnpm安装express 和 http-proxy-middleware。命令后面加了--save,要是拿了我源码的可以直接cnpm install 或者npm install即可全部安装。 

(4)编写index.html页面 还有 给目录结构大家参考一下

<!DOCTYPE html>

<html>
<head>
	<title>users</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
	<div class="table-responsive">
  <table class="table" id="myTable">
    <th></th>
    <tr><td>id</td><td>username</td><td>password</td><td>phone</td></tr>
  </table>
</div>
<script src="js/jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$.ajax({
		url:'http://localhost:8080/api/users',
		//url:'http://localhost/api/users',
		// type:'get',
		async:true,
		dataType: 'json',
        //crossDomain: true,
		success:function(data){
			console.log(data);
			for(var i=0;i<data.length;i++){
				$('#myTable').append('<tr><td>'+data[i].id+'</td><td>'+data[i].username+'</td><td>'+data[i].password+'</td><td>'+data[i].phone+'</td></tr>');
			}
			//$('#myTable').append
		},
		error:function(data){
			console.log(data);
			//console.log(data[0].id);

		}
	})
	});
</script>
</body>

	


</html>

(5)是最核心的一步,编写index.js。在这里说明一下这个不一定是叫index.js 你也可以叫main.js,不过最好跟你(2)填入的entry point 名字对应。

//引用模块
var express = require('express')
var proxy = require('http-proxy-middleware')
var app  = express()
//静态资源直接访问
//如dist/js/jquery.js  访问路径为 http://localhost/js/jquery.js 在script标签中src="js/jquery.js"
app.use(express.static('dist'))

//api子目录下的都是用8080代理 
// 在我的源代码后端是8080端口开启 其中有两个controller  UserController  TestController
//UserController requestMapping是"/api"  访问http://localhost/api/users 相当于访问 http://localhost:8080/api/users
//TestController requestMapping是"/test" 访问http://localhost/test/users不能访问
//
const apiProxy = proxy('/api', { target: 'http://localhost:8080',changeOrigin: true });//将服务器代理到localhost:8080端口上[本地服务器为localhost:3000]
app.use('/api/*', apiProxy);


app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/src/" + "index.html" );
})

app.get('/login.html', function (req, res) {
	res.sendFile( __dirname + "/src/" + "login.html" ); 
})
// app.get('*',function(req,res){
// 	res.sendFile( __dirname + "/src/" + "index.html" );
// })

app.listen(80,function(){
	console.log('connect successfully')
})

app.use(express.static('dist'))

//静态资源直接访问
//如dist/js/jquery.js  访问路径为 http://localhost/js/jquery.js 在script标签中src="js/jquery.js"

const apiProxy = proxy('/api', { target: 'http://localhost:8080',changeOrigin: true });//将服务器代理到localhost:8080端口上[本地服务器为localhost:3000]
app.use('/api/*', apiProxy);

//api子目录下的都是用8080代理 
// 在我的源代码后端是8080端口开启 其中有两个controller  UserController  TestController
//UserController requestMapping是"/api"  访问http://localhost/api/users 相当于访问 http://localhost:8080/api/users
//TestController requestMapping是"/test" 访问http://localhost/test/users不能访问
 

当然也可以把页面也放进去dist当作静态资源访问

(6)运行后端服务器,然后在前端项目根目录下cmd 命令"nodex index.js"

表示成功运行

首先访问http://localhost:8080/api/users

然后访问 http://localhost/api/users

访问 http://localhost/test/users 失败

访问http://localhost:8080/test/users 成功

以上表明后端服务器运行和node 对/api的代理成功了

访问http://localhost/index.html也成功展现数据

以上是我前后端分离的小小总结

最后,放上我的源码地址https://github.com/wayleung/test-demo.git,喜欢的可以star一下,感谢。

猜你喜欢

转载自blog.csdn.net/weixin_37760377/article/details/82782122