Nginx+tomcat 实现前后端分离(解决跨域)
程序员文章站
2022-07-10 08:07:35
...
工具:
nginx-1.15.3
apache-tomcat-9.0.11
代码准备:
前端
新建前端文件,结构如下
index.html代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#b01").click(function(){
htmlobj=$.ajax({url:"http://localhost/restdemo/RestDemo",async:false});
$("#myDiv").html(htmlobj.responseText);
});
});
</script>
</head>
<body>
<div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>
<button id="b01" type="button">改变内容</button>
<a href="demo.html">demo</a>
</body>
</html>
后端
新建后端web项目,结构如下
RestDemo.java代码如下
package com.zq.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RestDemo
*/
public class RestDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RestDemo() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
nginx配置
静态网页请求发送到nginx静态目录html中,restdemo项目为后台请求,转发到后台
访问测试:
浏览器输入地址:http://localhost/frontdemo/
点击“改变内容”按钮,可以看到文本通过ajax调通了
本文资源下载:Nginx1.15.3+Tomcat9.0.11前后端分离及测试源码
扩展:
Windows环境:
nginx启动:start nginx.exe
检查配置:nginx.exe -t
重启:nginx.exe -s reload
Linux环境:
https://www.cnblogs.com/codingcloud/p/5095066.html
推荐阅读
-
解决vue+springboot前后端分离项目,前端跨域访问sessionID不一致导致的session为null问题
-
springboot解决前后端分离时的跨域问题
-
前后端分离djangorestframework——解决跨域请求
-
vue+springboot前后端分离实现单点登录跨域问题解决方法
-
vue2 前后端分离项目ajax跨域session问题解决方法
-
前后端分离cors解决跨域问题
-
vue-cli+spring boot前后端分离跨域及session丢失解决办法
-
前后端分离与跨域的解决方案(CORS的原理)
-
vue - axios 前后端分离 跨域访问的实现
-
Nginx+tomcat 实现前后端分离(解决跨域)