gpt4 book ai didi

javascript - 在node js中处理跨域ajax post

转载 作者:行者123 更新时间:2023-12-03 09:25:12 25 4
gpt4 key购买 nike

我的 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 中没有未定义的参数

我无法从 Node 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');
});

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>

关于javascript - 在node js中处理跨域ajax post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com