Same origin Policy & Cross domain

What is JSONP?

JSONP (JSON with Padding) is a “usage mode” of JSON that allows web pages to retrieve data from other domains. — Wikipedia

JSONP core principles

  • scriptLabels are not affected by the same origin policy.
  • Dynamic insertion intoDOMIn thescriptScripts can be executed immediately.

Implementation steps

  1. The client creates oneJavaScriptFunction to receive data returned by the server.
function onResponse(data) {
    // do something
}
Copy the code
  1. Client dynamic insertionscriptThe tag performs the request.
var script = document.createElement('script')
script.src = 'protocal://domain:port/path? callback=onResponse'
document.head.appendChild(script)
document.head.removeChild(script)
Copy the code
  1. The server concatenates the data and the JS callback function name into a string of function calls and returns it to the client.
app.get('/path'.function(request, response) {
    var data = getData()
    var callback = request.query.callback
    var result = `${callback}(The ${JSON.stringify(data)}); `
    response.send(result)
})
Copy the code
  1. The client received the packet. ProcedurescriptThe tag responds and automatically executes the callback function.

The disadvantage of the json

  • Can only useGETThe request.
  • Dynamically insertedscriptScripts may be injected with malicious code.