Cross domain CORS of ajax

Keywords: Javascript JSON

Cross domain

background

Same origin policy: client scripts of different domains cannot read or write to the other resource without explicit authorization
Due to the existence of browser homology policy, in some scenarios where cross domain data acquisition is required, some methods are needed to implement cross domain requests

Same domain: same protocol, same domain and same port

Cross domain approach 1-CORS

Give an example

Server A client code

<body>
<button id="btn">Click to load data</button>
<button id="btn-origin">Click to load data across domains</button>
<ul id="box"></ul>
<script>
//Object acquisition
var byId = (id) => document.getElementById(id);
var btn = byId('btn');
var btnOrigin = byId('btn-origin');
var box = byId('box');
//ajax function
function getData(callback, cors) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
            callback(JSON.parse(xhr.responseText), xhr);
        } else {
            console.log(xhr.status, xhr.statusText, xhr);
        }
    }
    xhr.open('get', `http://127.0.0.1:3000/${cors} '); / / different buttons pass different parameters in
    xhr.send(null);
}
//Direct access button event binding
btn.addEventListener('click', () => {
    getData((response) => {
    box.innerHTML = `<li>${response.result.data}</li>`;
}, ''); //cors parameter passed is null
});
//Cross domain access button event binding
btnOrigin.addEventListener('click', () => {
getData((response) => {
box.innerHTML = `<li>${response.result.data}</li>`;
}, '?cors=1'); //cors parameter passed
});
</script>
</body>

Server B server code

const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const app = new Koa()
const util = require('./util')
// bodyParser plug-in, which processes the data submitted by post
app.use(bodyParser())
app.use(async ctx => {
const url = ctx.url
util.log(`Access address: ${url}ï¼›Request method: ${ctx.method}`)
const origin = ctx.headers.origin //Get domain name
if (origin && ctx.query.cors) {
ctx.set('Access-Control-Allow-Origin', origin) //Meet the agreed conditions and set the response header
}
ctx.body = util.parse({
data: 'hello cors'
}, ctx.method)
})
app.listen(3000, () => {
util.log('Service start, open http://127.0.0.1:3000/')
})

Result demonstration

1. When you click directly to get data

No authorized access field in response header

2. When you click cross domain access

Server B echo response header with authorization field allowing server A to access

Posted by digibrain on Tue, 03 Dec 2019 12:23:10 -0800