我想使用 jQuery 向 mongodb 发出 Post 请求。 在应用程序 localhost:3000 上运行。 使用 Mongoose 我可以使用以下方式显示电影:
router.get('/', function(req, res, next) {
mongoose.model('Movie').find(function(err, titles){
res.render('testdb', { title: 'MYMusic',
className: 'index',
names: titles
});
console.log('names: ', titles);
});
});
但是当我想使用 jQuery 动态发布到我的数据库时:
$('.save-video-button').on('click', function(event) {
var obj = {
title: 'some title'
};
var URL = 'mongodb://localhost/mydatabase';
$.ajax({
url: URL,
type: "POST",
data: JSON.stringify(obj),
contentType: "application/json",
success: function(data) {
console.log('success --> data :', data);
},
error: function(xhr, text, err) {
console.log('error: ',err);
console.log('text: ', text);
console.log('xhr: ',xhr);
console.log("there is a problem whit your request, please check ajax request");
}
});
});
当我运行此 ajax 请求时,Google Chrome 开发工具控制台中显示错误:
XMLHttpRequest 无法加载 mongodb://localhost/mydatabase。仅以下协议(protocol)方案支持跨源请求:http、data、chrome、chrome-extension、https、chrome-extension-resource。
如何避免这种跨源请求?
谢谢!
最佳答案
好的,我明白了!对于有同样问题的人,不要忘记在服务器端有一个 router.post:
router.post('/', function(req, res){
var newmovie = res.body;
console.log(newmovie);
});
因此,当您进行调用时,您实际上可以传递 data = res。
关于javascript - 使用 jquery ajax 发布到 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710718/