利用express簡單實(shí)現(xiàn)同源請(qǐng)求
新建個(gè)origin.js, 導(dǎo)入express,添加個(gè)路由:
app.get('/home', (req, res)=> {
res.sendFile(__dirname+'/index2.html');
});
終端輸入node origin.js.
express設(shè)置監(jiān)聽端口是8000,打開http://127.0.0.1:8000/home就能訪問本地index.html,此時(shí)index2里簡單發(fā)起一個(gè)AJAX請(qǐng)求:
btn.onclick = function () {
const xhr = new XMLHttpRequest();
xhr.open('GET', '/data'); //此處不要補(bǔ)全http://127.0.0.1:8000,因?yàn)榫W(wǎng)頁端和后端已經(jīng)同源。
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
}
}
}
}
express繼續(xù)添加一個(gè)路由
app.get('/data', (req, res)=>{
res.send('數(shù)據(jù)');
})
此時(shí)就同源獲取了后端返回的 '數(shù)據(jù)'。
重點(diǎn)是,這里利用了nodejs打開了index.html,然后再index.html打開了同源的/data,自然可以訪問/data里返回的數(shù)據(jù)了。

浙公網(wǎng)安備 33010602011771號(hào)