JSONP implements cross-domain requests
Question raising
Due to the restriction of the same origin policy of the browser, non-same origin requests will cause cross-domain problems. Jsonp is a simple solution to solve this problem, but it is also a vulnerability, which is not supported by the official
The solution
This is implemented through some official tags that support cross-domain requests (such as script). The official rules for the meaning of these tags are not intended to implement cross-domain requests, but we implement them through these loopholes
The front-end code
</button> <div id="result"> </div> <script> $('button').eq(0).click(function(){ $. GetJSON (' http://127.0.0.1:8000/jquery-jsonp-server? callback=? ', function (data) {$(' # result '). The HTML (` name: ${data. The name} < br > campus: ${data. City} `)}); }); </script> </body>Copy the code
- The script tag requires the server to return JS code and execute it as it is returned
- Callback uses functions that are executed (typically for changes to the page), declared in the front-end page origin, and called by logic on the back-end (how? Look at cb in the code at the back end.
Back-end code
app.all('/jquery-jsonp-server',(request, response) => { // response.send('console.log("hello jsonp")'); Const data = {name: 'it is silicon valley, city: [' Beijing', 'Shanghai', 'shenzhen']}. // Convert data to a string let STR = json.stringify (data); // let cb = request.query.callback; Response. end(' ${cb}(${STR}) '); });Copy the code
CORS implementations cross domains
Official Document link
Own understanding
Without too deep understanding, I will wait for more in-depth study and then come back to the summary