繁体   English   中英

处理节点js中的跨域ajax帖子

[英]handle cross domain ajax post in node js

我的 app.js 具有以下用于发布的处理程序

app.all('/', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
});

app.options('*', cors());

var allowCrossDomain = function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    next();
};

app.use(allowCrossDomain);

var whitelist = ['http://myurl.net'];

var corsOptions = {
    origin: function (origin, callback) {
        var originIsWhitelisted = whitelist.indexOf(origin) !== -1; callback(null, originIsWhitelisted);
    }
};
app.post('/ValidateUser/users',cors(corsOptions) , function (req, res) {
    var db = req.db;
    var collection = db.get('userlist');

    collection.find({}, {}, function (e, docs) {
        res.json(docs);
    });

    res.send("Hey");
});

调用它的 html 页面具有以下代码

var user = { "bla":"bla"  };

function checkUser() {
    $.ajax({
        type:"POST",
        url: 'http://localhost:1337/validateuser/users',
        data: user,
        crossDomain: true,
        dataType:"jsonp"
        //jsonp: false,
        //jsonpCallback: 'jsonCallback'
    }).success(function (data) { console.log(data) });
};

当我保持断点并检查req.body ,它在 req.body 中没有未定义的参数

我无法从节点 js 中的 html 获取我发布的数据

使用 body-parser 模块获取数据,例如:

服务器.js:

var express = require('express');
var bodyParser = require('body-parser');
var db = require('./db'); //module that contains db connection config

var app = express();

app.use(bodyParser());

app.get('/', function(req, res) {
    res.sendFile('/index.html', {root: __dirname });
});

app.post('/users', function(req, res) {
    console.log(req.body); //req.body contains the user = {bla: 'bla'} object
    var user = req.body;
    var collection = db.get('userlist');
    collection.find(user, function (e, docs) {
        res.json(docs);
    });
    res.send("Hey");
});

var server = app.listen(3000, function() {
    console.log('listening');
});

索引.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script>
    var user = { "bla":"bla"  };
    function checkUser(data) {
        $.ajax({
            type:"POST",
            url: 'http://localhost:3000/users',
            data: data,
            dataType: "json"
        }).success(function (data) { console.log(data) });
    };
    checkUser(user);
    </script>

</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM