ajax跨域问题:No ‘Access-Control-Allow-Origin‘ header is present on the requested resource

88 阅读2分钟

今天在学习Ajax时,客户端发送请求总是报错。 No 'Access-Control-Allow-Origin' header is present on the requested resource. 我是用的是nodemon 和 express 框架来测试ajax请求。 以下是代码部分:

/* app.js */
//引入express框架
const express = require('express');
//引入路径处理模块
const path = require('path')
//创建web服务器
const app = express();

//静态资源访问服务器功能
app.use(express.static(path.join(__dirname, 'public')));
app.get('/first', (req,res) => {
    res.send('你好,这里是服务器,我收到了你的ajax请求');
    console.log('有请求发来,已响应');
});
//监听端口
app.listen(3000);
console.log('服务器启动成功')
/* demo04.html */
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>第一个ajax网页</title>
</head>

<body>
    <script type=text/javascript>
        // 创建ajax对象
        var xhr = new XMLHttpRequest();
        // 给对象安排方式和发送地址
        xhr.open('get', 'http://localhost:3000/first');
        console.log('准备发送:');
        // 发送请求
        xhr.send();
        console.log('已发送');
        // 获取响应的数据
        xhr.onload = function () {
            // xhr.responseText
            console.log('收到了服务器的内容:');
            console.log(xhr.responseText);
        };
        // console.log(1);
    </script>
</body>

</html>

仔细检查了代码,发现没有问题,服务器端也可以正常响应,但是客户端总是报错。 我在根据报错信息搜索了有关问题,发现如下一篇文章。跨域详解 been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource 问题所在: 我使用了live Server 插件打开的demo04.html,live Server使用5500端口,而express监听3000端口,5500端口向3000端口请求资源,是跨域访问资源问题。 浏览器为了安全,限制了本站点。

上面的意思就是 你访问一个什么地址被CORS 协议阻止, 没有 在Hearder 里面发现 Access-Control-Allow-Origin 的参数的 资源

跨域问题的原因:浏览器出于安全考虑,限制访问本站点以为的资源。

比如你有一个 网站 127.0.0.1:8080/ , 并且上面挂了一个页面 ,那么在这个页面中 ,你只访问 本站点的 资源不会受到限制,但是你如果访问其他站点,比如 127.0.0.1:8081 的资源就会受到限制。

解决方法: 使用express监听的: http://localhost:3000/ 后跟路由访问文件目录即可。