从 Backbone 发送发布请求.js返回跨域错误

Sending a post request from Backbone.js is returning a cross domain error

本文关键字:返回 js 错误 Backbone 布请求 请求      更新时间:2023-09-26

我正在使用express.js作为后端和骨干.js作为前端,MongoDB作为数据库。根据我传入的参数获取单个帖子或帖子集合没有问题,但是每当我尝试 POST 请求时,我都会收到错误。我已经厌倦了在我的模型上调用 .save(),但是,我遇到了跨站点域错误。这是我代码的一部分

var Post = Backbone.Model.extend({
  url: "/posts/new"
});
var Posts = Backbone.Collection.extend({
  url: "/categories/all"
});
var PostView = Backbone.View.extend({
  model: new Post(),
  template: JST["post"],
  new_template: JST["new_post"],
  el: $(".page"),
  events: {
    "click .to_category": "updateCurrentCategory",
    "submit .new_post": "create"
  },
  create: function (e){
    e.preventDefault();
    showLoader();
    console.log("subbmited");
    this.model.save();
    hideLoader();
  }
}

您需要在 express.js 应用程序标头部分中包含跨域策略:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
  next();
});
app.get('/', function(req, res, next) {
  // Handle the get for this route
});

然后,如果您使用 ajax 请求提交发布数据,则必须将crossDomain设置为 true

如果您希望在同一上强制跨域请求(例如 JSONP) 域中,将跨域的值设置为 true。这允许,对于 例如,服务器端重定向到另一个域。(添加的版本: 1.5)

http://api.jquery.com/jquery.ajax/

$.ajax({
    type: 'POST',
    url: 'your/url',
    crossDomain: true, // set it to `true`
    dataType: 'json',
    success: function(responseData, textStatus, jqXHR) {
        console.log('success');
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});