简体   繁体   English

如何设置基于URL的jQuery Ajax头授权?

[英]How to set jquery ajax headers authorization based on url?

I have a wordpress website that has woocommerce ajax requests on its Order Page. 我有一个wordpress网站,其“订购页面”上有woocommerce ajax请求。 The website has a staging domain and a live domain. 该网站有一个暂存域和一个实时域。

$(function(){
   var root_url = 'https://'+window.location.hostname;
   console.log(root_url);
});

Ajax Request sample for staging: Ajax请求分期样本:

$.ajax({
  type: 'GET',
  url: https://staging-mywebsite.net/wp-json/wc/v2/products?category=504,
  cache: false,
  beforeSend: function(jqXHR, settings) {
  },
  headers: {"Authorization": "Basic " + btoa("ck_123" + ":" + "cs_123") // staging},
  success: function(data) {
  }
});

Ajax Request sample for Live site: Ajax申请Live网站样本:

$.ajax({
  type: 'GET',
  url: https://livewebsite.com/wp-json/wc/v2/products?category=504,
  cache: false,
  beforeSend: function(jqXHR, settings) {
  },
  headers: {"Authorization": "Basic " + btoa("ck_456" + ":" + "cs_456") // staging},
  success: function(data) {
  }
});

The live and staging website has different username and password on the headers property. 现场直播网站在headers属性上具有不同的用户名和密码。

Do you know how can I set a condition or a global variable for the headers property depending on the domain? 您知道如何根据域为headers属性设置条件或全局变量吗?

Any help is appreciated. 任何帮助表示赞赏。 Thanks 谢谢

Have you tried using the document.domain property? 您是否尝试过使用document.domain属性? I'm thinking something like this: 我在想这样的事情:

var headers = {"Authorization": "Basic " + btoa("ck_456" + ":" + "cs_456")} // Assume live site
if( document.domain === "staging-mywebsite.net" ){
  headers = {"Authorization": "Basic " + btoa("ck_123" + ":" + "cs_123")} // Use staging instead
}

And then inside your AJAX request you use the variable instead. 然后在您的AJAX请求中,您改为使用变量。

...
headers: headers,
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM