Jsonp method to solve cross domain problems

Is it mine, Mimi 2021-04-07 21:42:40
jsonp method solve cross domain

What is homology strategy

Source : agreement 、 domain name 、 Port number .
When the data response comes back, the browser will detect the source of the requested data and the sender of the request HTML Whether the source of the page is consistent .
Wikipedia's explanation is as follows , For details, please refer to Wikipedia - The same-origin policy

1.png One thing to note is that , Open the access link directly in the browser , It's equivalent to direct access , You can see the data . however , When sending a request for access from a page , Will determine whether it is cross domain , If it's cross domain , The request was actually sent out , The server also responded , But the response was intercepted by the browser , Because there is a homologous policy in the browser's security policy .

JSONP(JSON+Padding) Methods and principles

JSONP Method : utilize script Tags are not subject to the same origin policy , stay HTML Dynamic generation in the page script label , utilize script Labeled src Property to access the server side , The server will return a function call (fuName( Returned data )), And put the response data in the parameters of the callback function ,HTML The page gets the response data through the parameters of the callback function .
Here are two explanations I've seen jsonp In the video :
YouTube- Cross domain Explained jsonp Method in HTML Page and server data interaction ,
YouTube-jsonp Explained jsonp Method to access an external interface .
notes :img、link and script Tags are not restricted by the same origin policy , Allow cross domain loading .
If there is something unclear in my story , Also can reference Blog , The following is a partial screenshot of the blog .


Code implementation

jsonp Method code implementation

Connect with the city wis.qq.com/city/like For example , The required parameters of the interface are shown in the figure below , Source of the figure Blog

2.png First step , To directly access the interface once to see what the callback function name is ;
This interface is in Tencent weather Call in the address search bar of , So we call the interface once in the search box , View the request header information in the network , It is found that the callback function name is callback, Here's the picture :

4.png We can then confirm that the address to be visited should be :wis.qq.com/city/like?s…
The second step , Take Hong Kong as an example .

function getData(data) {
let script = document.getElementById("jsonp")
script.parentNode.removeChild(script) // Remove the new node
// establish script node
let script = document.createElement("script")
script.id = "jsonp"
script.src = "https://wis.qq.com/city/like?source=pc&city= Hong Kong &callback=getData"
// take script Add nodes to DOM In the tree , Otherwise, the node will not take effect
 Copy code 

Here's the picture , It is the request header and response data of this call interface .



jsonp Function encapsulation

According to the above method , Every time you call jsonp Repeat the above code , Very inconvenient , So we can further encapsulate the method .
According to the above ideas , We need four parameters in all , visit url、 Access parameters 、 The parameter name of the callback function defined by the interface 、 Callback function parameter body .
( notes : Callback function parameter names are different for different interfaces , Most of the interface callback function parameter names I see are callback, There are exceptions. , For example, the callback function parameter name of Baidu search box is cb, Here's the picture 7.png) The encapsulated code is as follows :

url: Access link
params: Parameter name / Parameter values json Formatted data
cbName: The callback function parameter name specified when accessing the interface
cbFunction: Callback function specific function body
function jsonp(url, params, cbName, cbFunction) {
let strParams = ""
// Traverse json Format parameters , Combined into a formatted string
for (let key in params) {
// After the last traversal, there will be one more after the end of the last parameter &, Followed by callback function parameters
strParams += key + "=" + params[key] + "&"
// Math.random(): return 0 ~ 1 Random number between , Reduce the cost of calling multiple jsonp Repeat rate of callback function name on request
let fnName = cbName + Math.random().toString().replace('.', '')
// establish script node
let script = document.createElement("script")
script.src = url + "?" + strParams + cbName + "=" + fnName
// take script Add nodes to DOM In the tree , Otherwise, the node will not take effect
// Add the callback function to the global scope
window[fnName] = cbFunction
// When this script Remove the tag when it is loaded
script.onload = () => script.parentNode.removeChild(script)
 Copy code 

The call method is as follows :

jsonp("https://wis.qq.com/city/like", {
"source": "pc",
"city": " Hong Kong ",
}, "callback",
(data) => console.log(data))
 Copy code 

Problems to pay attention to

  1. Callback functions must be placed in the global scope , Because the server will return to the page after receiving the callback function script Middle search , If you don't write it, you can't find it in the global scope ;
  2. Callback function parameter names are different for different interfaces , To encapsulate a function, this place needs to be used as a separate parameter .
本文为[Is it mine, Mimi]所创,转载请带上原文链接,感谢

  1. Behind the miracle of the sixth championship is the football with AI blessing in the Bundesliga
  2. An easy to use Visual Studio code extension - live server, suitable for front-end gadget development
  3. 用 Python 抓取公号文章保存成 HTML
  4. User login of front end spa project based on Vue and Quasar (2)
  5. Summary of common selectors in CSS
  6. Using Python to grab articles with public number and save them as HTML
  7. To "restless" you
  8. 【免费开源】基于Vue和Quasar的crudapi前端SPA项目实战—环境搭建 (一)
  9. 【微信小程序】引入阿里巴巴图标库iconfont
  10. layui表格点击排序按钮后,表格绑定事件失效解决方法
  11. Unity解析和显示/播放GIF图片,支持http url,支持本地file://,支持暂停、继续播放
  12. 【vue】 export、export default、import的用法和区别
  13. [free and open source] crudapi front end spa project based on Vue and Quasar
  14. [wechat applet] introduces Alibaba icon library iconfont
  15. Layui table click Sort button, table binding event failure solution
  16. Element树形控件Tree踩坑:修改current-node-key无效
  17. Unity parses and displays / plays GIF images, supports HTTP URL, supports local file: / /, supports pause and resume playback
  18. Element树形控件Tree踩坑:修改current-node-key无效
  19. The usage and difference of export, export default and import
  20. Element tree control: invalid to modify current node key
  21. Element tree control: invalid to modify current node key
  22. linux下安装apache(httpd-2.4.3版本)各种坑
  23. How to install Apache (httpd-2.4.3) under Linux
  24. 程序员业余时间写的代码也算公司的?Nginx之父被捕引发争议
  25. Nacos serialize for class [com.alibaba.nacos.common.http.HttpRestResult] failed.
  26. Do programmers write code in their spare time? Controversy over the arrest of nginx's father
  27. Nacos serialize for class [ com.alibaba.nacos . common.http.HttpRestResult ] failed.
  28. Seamless management of API documents using eolink and gitlab
  29. vue 的基础应用(上)
  30. 28岁开始零基础学前端,这些血的教训你一定要避免
  31. Basic application of Vue
  32. Starting at the age of 28, you must avoid these bloody lessons
  33. Ubuntu 16.04 can not connect to the wireless solution and QQ installation
  34. Industry security experts talk about the rapid development of digital economy, how to guarantee the security of data elements?
  35. 利用Vue实现一个简单的购物车功能
  36. Behind the "tireless classroom" and teacher training, can byte education really "work wonders"?
  37. Using Vue to realize a simple shopping cart function
  38. 【css】伪类和伪类元素的区别
  39. 【css效果】实现简单的下拉菜单
  40. 【vue】父子组件传值
  41. The difference between pseudo class and pseudo class elements
  42. [CSS effect] simple drop-down menu
  43. [Vue] value transfer by parent-child component
  44. 【css】设置table表格边框样式
  45. 【css】修改input,textarea中的placeholder样式
  46. vue-router的两种模式(hash和history)及区别
  47. CSS3的滤镜filter属性
  48. [CSS] set table border style
  49. [CSS] modify the placeholder style in input and textarea
  50. Two modes of Vue router (hash and History) and their differences
  51. Filter property of CSS3
  52. 全局安装gulp 报错问题解决
  53. Solution of error report in global installation of gulp
  54. 18个好用的自定义react hook
  55. 你应该知道的常用服务器HTTP状态码?
  56. 18 user defined react hooks
  57. What HTTP status codes should you know about common servers?
  58. 手把手教你打造属于自己团队的前端小报系统
  59. Hand in hand to teach you to build your own front-end tabloid system
  60. In 2021, enterprise SEO actual operation, how to less update, batch ranking regional words?