Jsonp of cross-domain technology

With the rapid development of the front-end, the application of jsonp technology has become less and less in recent years, but we still need to understand jsonp in detail, which is of great significance to how we cooperate with the back-end

jsonp

As we all know, jsonp is a way to obtain data across domains. As for why there are cross domains and why cross domains, I won’t give a detailed explanation here.

Don't talk nonsense, go directly to the
code

function backFn(data) {
    
    
  console.log(data)
}

<script src="httpsL//wwww.接口地址.com/?参数&callback=backFn"></script>

Code behind

这里用node为例子

服务器名称.get('/接口地址',(request,response) => {
    
    
  fs.readFile('数据地址',(error,data) => {
    
    
    let resData = `backFn(${
      
      JSON.parse(data.toString())})`
    response.send(resData)
    console.log('请求已响应')
  })
})

Don't you feel so confused? Don't be afraid, let's analyze it bit by bit

  • The principle of jsonp is to dynamically create a script tag, request data by writing the interface address on the src attribute
  • The requested interface address must be followed by a callback=backFN
  • The backFn is a function you have written in the foreground. This function is used to receive the parameters returned by the request. This parameter should be negotiated with the background
  • Callback should also be negotiated with the background, which is like a signal
  • The data format returned by the background must be backFn (included data) format

There are strict requirements on the data format returned by the backend.
Take a closer look and see if you are familiar with backFn(). Is it equivalent to directly executing the backFn function that we have written in the foreground and treating the data
as Passed in as a parameter

This is the principle of jsonp, does it feel clear?

Guess you like

Origin blog.csdn.net/m0_47883103/article/details/108270869