springboot + nginx前后端分离

1、技术:springboot、nginx;

练习springboot前后端分离,且用nginx代理部署,实现前后端分离。

控制层添加json数据,并返回json.

@RestController
@RequestMapping("/student")
public class StudentController {

    @RequestMapping("/studentById")
    public JSONObject selectStudentById(String id, HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");

        /*
    
{   "name":"smith".   "age":30,   "sex":"男" }
     */ JSONObject jsonObject = new JSONObject(); jsonObject.put("name","smith"); jsonObject.put("age","30"); jsonObject.put("sex","男"); return jsonObject; } }

2、安装nginx。(过程省略)

2.1 在D:\xxxx\nginx-1.18.0\html 这个文件下添加一个页面 users.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <title>layui在线调试</title>
  <style>
    body{margin: 10px;}
    .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
  </style>
  <script src="/js/jquery.js"></script>
</head>
<body>
 
<button id="btn" onclick="threeFn()">点我</button>
<h3 id="aaa"></h3>

<script>
 
    function threeFn(){
        alert("请求了!!!");
        //向服务端发送删除指令
        $.ajax({
            type: "get",
            url: "/oa/student/studentById",
            dataType:'json', 
            success: function (data) {
                alert(data.name);    
          //取json中的name,打印在页面中             
         document.getElementById("aaa").innerHTML=data.name;
} }); } </script> </body> </html>

2.2 nginx的配置文件nginx.conf配置

#配置文件读取根路径下的静态文件 root后面的html,意思是nginx下的html文件夹
location / { root html; index index.html index.htm; }
# 配置代理地址 注意:oa是代表下面的 IP+port,请求url如页面中所示 port则是springboot中设置的或者默认的

location /oa/ {              
               proxy_pass http://127.0.0.1:8384/;  #注意:使用代理地址时末尾记得加上斜杠"/"。      
        }

3、启动nginx,浏览器输入http://127.0.0.1/users.html,如图所示

点击按钮

 nginx代理成功。。。

一步步继续深入学习。

猜你喜欢

转载自www.cnblogs.com/liyh321/p/13177284.html