Workaround 1: Use CORS to pre-declare that sharing is possible
SetHeader (‘ access-Control-allow-origin ‘, ‘HTTP :xx urlxxx’)
To make it available to everyone, request. Referer can be used to get the visitor’s website, set to the second parameter of setHeader
Then we can use AJAX to get it.
Solution 2: Use JSONP for setup
JSONP solves the problem that data cannot be shared in the way of CORS under IE
Its principle is the first step, let the other party write the file to a JS file, and then reference the other party’s JS file through the party, because the JS file is referable, so as to obtain the internal data of the other party.
The detailed technique is to set a callback function on the local side, and then call the callback function on the other side, modify the parameters of the callback function to the JSON data response.write to be transmitted, and then transfer can be realized.
For example: this sets a function
window.callback(data)=>(console.log(data))
Copy the code
Create a new js file and write the contents of the function:
callback("{data}")
Copy the code
The other party then writes in the server code for the response:
If (path === '/friends.js') {response.statusCode = 200 Response.setheader (' content-type ', 'text/javascript; Charset = utF-8 ') let string = fs.readfilesync ('./friends.js').tostring ( Fs.readfilesync ('./ a.jaxon ').toString() // Get json data to send let string2 = string.replace('"{data}"', data) Replace the parameters in the JSON file. Response.write (string2) // Write the replacement to response.end()}Copy the code
Since we set a function with the js file of the other side, and reference the JS file of the other side, it is equivalent to the other side executed a callback function set by us, and transferred the data to us for acquisition in the legal form of JS file.
The advantages of the json
The advantages are compatibility with IE and cross-domain
Cons: Post is not supported because of script reference transfer.