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

时间:2015-07-29 13:30:12

标签: javascript node.js express cors

我的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中获取我发布的数据

1 个答案:

答案 0 :(得分:1)

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

server.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');
});

的index.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>