Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Separation of Front and back ends by JavaScript

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how JavaScript realizes the separation of front and back ends". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

Case of front and rear separation

Now think of yourself as the front end and develop a simple front-to-back page that displays a list of student information.

the first step

Write a static page that displays the table

number name age gender request data

function req(){ document.getElementById("img").src = "img/timg.gif"; $.ajax({ url:"http://localhost:8080/MyServer/getData", success:function(data){ console.log(data); document.body.insertAdjacentHTML("beforeend","%".replace("%",data)); document.getElementById("img").src = ""; }, error:function(err){ console.log(err); document.getElementById("img").src = ""; } }); }

现在身份切换回后端开发用于获取表格数据的接口

创建web项目

创建Servlet

引入fastjson

创建一个bean类

创建一堆bean放入列表中

将列表转为json字符串 返回给前端

Servlet代码

package com.kkb;import java.io.IOException;public class AServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { String s = "{\"name\":\"jack\"}"; response.getWriter().println(s); }}

启动服务,测试访问,会发现页面上没有显示服务器返回的结果….

跨越问题

打开浏览器检查页面会发现没有输出服务器返回的消息而是,出现了一个错误信息,这就是前后端分离最常见的跨越问题

什么是跨域

跨越问题之所以产生是因为浏览器都遵循了同源策略

同源策略:

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

同源策略是浏览器的行为,是为了保护本地数据不被JavaScript代码获取回来的数据污染,浏览器会先发送OPTION请求进行预检查,判断服务器是否允许跨域,如果允许才发送真正的请求,否则抛出异常。

简单的说:

同源策略是浏览器的核心安全机制,其不允许在页面中解析执行来自其他服务器数据

如何判断是否跨域

当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域

同源限制:

无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB

无法向非同源地址发送 AJAX 请求

什么时候产生跨域问题:

浏览器在解析执行一个网页时,如果页面中的js代码请求了另一个非同源的资源,则会产生跨越问题

而浏览器直接跳转另一个非同源的地址时不会有跨域问题

解决跨越问题

既然禁止跨域问题是浏览器的行为,那么只需要设置浏览器允许解析跨域请求的数据即可,但是这个设置必须放在服务器端,由服务器端来判断对方是否可信任

在响应头中添加一个字段,告诉浏览器,某个服务器是可信的

package com.kkb;import java.io.IOException;public class AServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { response.setHeader("Access-Control-Allow-Origin","*"); String s = "{\"name\":\"jack\"}"; response.getWriter().println(s); }}

其值可以是某个或多个指定的域名,也可以是*表示信任所有地址

其他相关设置

//指定允许其他域名访问'Access-Control-Allow-Origin:http://XXX.XXX.XXX'//一般用法(*,指定域,动态设置),注意*不允许携带认证头和cookies//预检查间隔时间'Access-Control-Max-Age: 1800'//允许的请求类型'Access-Control-Allow-Methods:GET,POST,PUT,POST'//列出必须携带的字段'Access-Control-Allow-Headers:x-requested-with,content-type'

解决了跨越问题后再来完善上面的案例

Servlet代码:package com.kkb;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import java.io.IOException;import java.util.ArrayList;public class AServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { //允许来自任何主机的跨越访问 response.setHeader("Access-Control-Allow-Origin","*"); //设置响应类型为json数据 response.setContentType("application/json;charset=utf-8"); //学生信息 ArrayList students = new ArrayList(); Student stu1 = new Student("s1","jack",20,"man"); Student stu2 = new Student("s2","tom",22,"girl"); Student stu3 = new Student("s3","jerry",10,"woman"); Student stu4 = new Student("s4","scot",24,"boy"); students.add(stu1); students.add(stu2); students.add(stu3); students.add(stu4); response.getWriter().println(JSON.toJSONString(JSON.toJSONString(students))); }}HTML代码 编号 名字 年龄 性别

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report