ajax跨域报错是什么问题

跨域总是报错,我检查了很多遍都没有解决,响应头也没有敲错,请问是什么问题?


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #result{
            width: 200px;
            height: 200px;
            border: solid 1px blue;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>

    <script>
        //获取button元素
        const btn=document.getElementsByTagName('button')[0];
        //绑定事件
        btn.onclick=function(){
            //1.创建对象
            const xhr=new XMLHttpRequest();
            //2.初始化 设置请求方法和url
            xhr.open('GET','http://127.0.0.1:8000/server');
            //3.发送
            xhr.send();
            //4.事件绑定 处理服务端返回的结果
            //readystate是xhr对象中的属性,表示状态0 1 2 3 4
            xhr.onreadystatechange=function(){
                //判断(服务器返回所有的结果)
                if(xhr.readyState===4){
                    //判断响应状态码 200 404 405 
                    //2xx 成功
                    if(xhr.status>=200 && xhr.status<=300){
                        //处理结果 行 头 空行 体
                        console.log(xhr.status);//状态码
                        console.log(xhr.statusText);//状态字符串
                        console.log(xhr.getAllResponseHeaders);//所有响应头
                        console.log(xhr.response);//响应体
                    }
                }
            }
        }
    </script>
</body>
</html>

const  express=require('express');
const app=express();
//创建路由规则
app.get('/server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Controll-Allow-Origin','*');
    //设置响应
    response.send('hello ajax');
})
//启动服务器
app.listen(8000,()=>{
    console.log("服务器已启动");
})

img

因为你的跨域设置写错了,应该是Access-Control-Allow-Origin,你的Control拼错了…

你的html 是怎么打开,如果是直接把文件用浏览器打开 当前域名就是 file://xx 那这个肯定是跨域的。
你可以把 html放到 express 的静态目录,这样就没有跨域的问题了

https://blog.csdn.net/xiaowuwjw/article/details/122814302

看看这个 你请求头 再设置一下

前端跨域的话可以让后端解决下