1. Jsonp cross-domain implementation

1. Create a callback method

 function getData(data){
        console.log(data,'koko')}Copy the code

2. Dynamically create a script tag and insert it at the end of the body

let script=document.createElement('script')

script.src='http://localhost:3000? callback=getData'

document.body.appendChild(script)
Copy the code

3. Backstage, set up a server with KOA

const Koa=require('koa')

let app=new Koa()

app.use((ctx)=>{

    let callback=ctx.query.callback
    let data={
        name:"Hu Positive",
        age:18,
        sex:'male'
    };
    let dataStr=JSON.stringify(data);
let res=callback+"("+dataStr+")";
 ctx.body=res
})

app.listen(3000,()=>{
    console.log('http://localhost:3000')})Copy the code

Implementation principle:

Step1: create the callback method

Step2: Insert the script label

Step3: The background receives the request, parses the callback method passed by the front end, returns the call of the method, and passes the data as parameter to the method

Step4: the front end performs the method call returned by the server