报错跨域问题

如下所示

clipboard.png

user.js

var http = require("http");
var fs = require("fs");
var querystring = require('querystring');

var str = 'empty';
http.createServer(function (req, res) {
    // // 定义了一个post变量,用于暂存请求体的信息
    var post = '';
    // // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
    req.on('data', function (chunk) {
        post += chunk;
    })
    // // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
    req.on('end', function () {
        post = querystring.parse(post);
        console.log(post);
        console.log(post.name)
        res.writeHead(200, {
            "Content-Type": 'application/json ',
            // "Content-Type": 'text/plain ',
            'charset': 'utf-8',
            //可以解决跨域的请求
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
            'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
        });
        // if (!post) {
        //     str = fs.readFileSync('./user.json');
        // } else {
        str = fs.readFileSync('./user.json');
        // }
        console.log(str.username);

    })
    if (post.name == str.username && post.password == str.password) {
        str = {
            "code": '1',
            "message": "ok"
        };
        res.write(String(str));
    } else {
        str = {
            "code": '0',
            "message": '用户名或密码不正确'
        };
        res.write(String(str));
    }

    // res.write(str);

    res.end();
}).listen(3000);
console.log("Server has started.port on localhost:3000");

user.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $.ajax({
            url: "http://127.0.0.1:3000",
            type: "POST",
            data: {
                name: 'wuyu',
                password: '123456'
            },
            dataType: "json",
            success: function (data) {
                $('body').html(`<h1>${data.username}</h1>`);
            },
            error: function (e) {
                console.log(e);
            }
        });
    </script>
</body>

</html>
阅读 4.6k
3 个回答

跨域条件

  1. 域名
  2. 协议。你本地是ftp协议吧。
  3. 端口。默认端口是80吧,你访问的3000

再说你的为什么写了不管用。CORS其实是在OPTIONS的嗅探请求里面给返回的。

Access to XMLHttpRequest at 'http://127.0.0.1:3000/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
话说这个错误重点是from origin 'null'

1:换个火狐浏览器试试?
2:静态文件也部署到一个服务器
3: 你的那种方法写不上,换另一个答案的方式可以。
clipboard.png


我express的跨域没问题。
$.ajax({url: 'https://www.lilnong.top/cors/1'})

看上去是这里覆盖了。删了就好了
clipboard.png

// Create our server
const server = http.createServer(function(req,res){
    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    if ( req.method === 'OPTIONS' ) {
        res.writeHead(200);
        res.end();
        return;
    }

    // ...
});

想要自己写个接口使用,东拼西凑貌似问题不少~~
后面又找了一个实现了想要的效果

var express = require('express');
var app = express();
var fs = require("fs");
var querystring = require('querystring');


// 设置跨域访问
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

var json = JSON.parse(fs.readFileSync('./user.json'));
var result = JSON.parse(fs.readFileSync('./result.json'));
console.log('jsonuser:', json);
console.log('resultjson:', result);

app.post('/user', function (req, res) {
    var post = '';
    req.on('data', (chunk) => {
        post += chunk;
    })

    req.on('end', () => {
        post = querystring.parse(post);
        console.log('post', post);
        if (post.name == json.username && post.password == json.password) {
            json = {
                "code": "1",
                "message": "ok"
            };
        } else {
            json = {
                "code": '0',
                "message": '用户名或密码不正确'
            };
        }
        res.json(json);

    })
});

app.get('/detail', (req, res) => {
    res.status(200),
        res.json(result)
})

// 配置服务端口

var server = app.listen(3002, () => {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
})
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $.ajax({
            url: "http://localhost:3002/detail",
            type: "GET",
            dataType: "json",
            success: function (data) {
                console.log(data);
                // $('body').html(`<h1>${data}</h1>`);
            },
            error: function (e) {
                console.log(e);
            }
        });
        $.ajax({
            url: "http://localhost:3002/user",
            type: "post",
            data: {
                name: 'wuyu',
                password: '123456'
            },
            dataType: "json",
            success: function (data) {
                console.log(data);
                // $('body').html(`<h1>${data}</h1>`);
            },
            error: function (e) {
                console.log(e);
            }
        });
    </script>
</body>

</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题