【问题标题】:ajax post with jquery to mongodb带有 jquery 的 ajax 发布到 mongodb
【发布时间】:2016-06-13 03:37:50
【问题描述】:

我想使用 jQuery 向 mongodb 发出 Post 请求。 在应用程序 localhost:3000 上运行。 使用猫鼬,我可以使用以下方法显示电影:

  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。跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https、chrome-extension-resource。

如何避免这个跨域请求?

谢谢!

【问题讨论】:

    标签: javascript ajax node.js mongodb express


    【解决方案1】:

    好的,我明白了!对于任何有相同问题的人,请不要忘记在您的服务器端有一个 router.post:

    router.post('/', function(req, res){
        var newmovie = res.body;
        console.log(newmovie);
    });     
    

    因此,当您拨打电话时,您实际上可以传递 data = res。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      • 2011-03-07
      • 2011-12-06
      相关资源
      最近更新 更多