Time: 2024-07-21 Sunday 14:49:01
Author: Jackasher
AJAX跨域问题
请求可以到达服务器,服务器正常响应,只是被浏览器拦截下来,浏览器为了保护浏览器,需要浏览器授权,我们可以看到是要求服务器设置响应头

所以在路由中设置响应头就可以解决了
1 2 3 4 5 6 7 8 9 10 11 12 13
| app.get("/student", (req,res) => {
console.log("收到get请求");
res.setHeader("Access-Control-Allow-Origin","*")
res.send({ status: "ok", result: STU_ARR }) })
|
最基本的ajax请求,正是因为是异步请求,才必须依靠回调函数来接受响应
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <script> const btn = document.getElementById("btn")
const root = document.documentElement btn.onclick = () => { const xhr = new XMLHttpRequest()
xhr.open("get","http://127.0.0.1:3000/student")
xhr.send()
xhr.responseType = "json"
xhr.onload = function(){
console.log(xhr.response); const result = xhr.response
const ul = document.createElement("ul") root.appendChild(ul)
for (const stu of result.data) { ul.insertAdjacentHTML("beforeend",`<li>${stu.id}-${stu.name}-${stu.age}-${stu.gender}-${stu.address}</li>`) }
} }
</script>
|