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
script
Labels are not affected by the same origin policy.- Dynamic insertion into
DOM
In thescript
Scripts can be executed immediately.
Implementation steps
- The client creates one
JavaScript
Function to receive data returned by the server.
function onResponse(data) {
// do something
}
Copy the code
- Client dynamic insertion
script
The 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
- 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
- The client received the packet. Procedure
script
The tag responds and automatically executes the callback function.
The disadvantage of the json
- Can only use
GET
The request. - Dynamically inserted
script
Scripts may be injected with malicious code.