我有一个用Wordpress构建的表单,它将数据发送到我在Node
上运行的远程服务器,然后处理该表单并将其发送到MongoDB
。
表格的处理类似于:
$('#theForm').submit(function(){
$.post('http://parthtoserver.com/api/postForm', formdata, function(returnedData){
if(returnedData === 'Success'){
// do success stuff here
}
});
});
My Node API的代码是:
exports.saveNewUser = function (req, res) {
console.log("Saving a new user");
var data = req.body;
var user = {
firstName: data.firstName,
lastName: data.lastName,
location: data.location,
email: data.email,
timezone: data.timezone
};
db.users.find({email:user.email}, function(err,record){
if(err){
console.log("There was an error finding record " + err);
}else if (record.length){
if(record[0].paidStatus === 1){
console.log("User already exists");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.send('UserExists');
}
}else{
db.users.save(user, function(err, record){
if(err){
console.log("There was an error: " + err);
}else{
console.log("Updated user");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.send('Success');
}
});
}
});
};
我认为'在另一个能够将数据发布到我的API的网站上没有任何伤害,然后将其保存到我的数据库中 - 但从安全的角度来看,我能做些什么来确保这不是恶意的码?
答案 0 :(得分:0)
无法判断您是否使用快递,但很可能是您。
在您的快递应用配置中:
app.use(express.basicAuth('username', 'password'));
// add your middleware to check referrer
app.use(myCheckReferrer);
function myCheckReferrer(req, res, next) {
if ( req.get('Referrer') === "somesite.com" )
next();
else
res.json(500, { error: 'Oops, no thank you!' })
}
阅读快速文档here
在客户端中,您需要添加基本授权标头,自动添加referrer
$.ajax({
url: 'http://parthtoserver.com/api/postForm',
type: 'post',
data: formdata,
headers: {
Authorization: "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
// the hash is base64 hash of the string "username:password"
// without the quote include the colon
},
dataType: 'json',
success: function(returnedData){
if(returnedData === 'Success'){
// do success stuff here
}
}
});