在主干上添加请求头 [英] add request header on backbone

查看:13
本文介绍了在主干上添加请求头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器有手动授权.我需要将我的服务器的用户名/密码放入我的主干请求中,以便它通过.我该怎么做?有任何想法吗?谢谢

My server has a manual authorization. I need to put the username/password of my server to my backbone request inorder for it to go through. How may i do this? Any ideas? Thank you

推荐答案

Backbone 中的模型使用 fetchsave 方法检索、更新和销毁数据代码>破坏.这些方法将实际请求部分委托给 Backbone.sync.在幕后,Backbone.sync 所做的就是使用 jQuery 创建一个 ajax 请求.为了合并您的基本 HTTP 身份验证,您有几个选择.

Models in Backbone retrieve, update, and destroy data using the methods fetch, save, and destroy. These methods delegate the actual request portion to Backbone.sync. Under the hood, all Backbone.sync is doing is creating an ajax request using jQuery. In order to incorporate your Basic HTTP authentication you have a couple of options.

fetchsavedestroy 都接受一个附加参数 [options].这些 [options] 只是一个包含在 jQuery ajax 调用中的 jQuery 请求选项字典.这意味着您可以轻松定义一个简单的方法来附加身份验证:

fetch, save, and destroy all accept an additional parameter [options]. These [options] are simply a dictionary of jQuery request options that get included into jQuery ajax call that is made. This means you can easily define a simple method which appends the authentication:

sendAuthentication = function (xhr) {
  var user = "myusername";// your actual username
  var pass = "mypassword";// your actual password
  var token = user.concat(":", pass);
  xhr.setRequestHeader('Authorization', ("Basic ".concat(btoa(token))));
}

并将其包含在您进行的每个 fetchsavedestroy 调用中.像这样:

And include it in each fetch, save, and destroy call you make. Like so:

 fetch({
  beforeSend: sendAuthentication 
 });

这会造成相当多的重复.另一种选择是覆盖 Backbone.sync 方法,复制原始代码并将 beforeSend 选项包含到每个 jQuery ajax 请求中.

This can create quite a bit of repetition. Another option could be to override the Backbone.sync method, copy the original code and just include the beforeSend option into each jQuery ajax request that is made.

希望这有帮助!

这篇关于在主干上添加请求头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆