如何从单个请求的 AJAX 调用中删除标头?

jdl*_*lam 5 javascript ajax jquery ruby-on-rails backbone.js

我正在构建一个应用程序,使用 Rails 和 Backbone 作为后端,需要用户登录才能访问某些页面。在经过用户身份验证的页面之一上,我进行了设置,以便他们可以通过输入数据在我的数据库中创建一个条目,然后将其发送到 Google 地图 API 以检索纬度和经度。

通过辅助函数,我检查用户是否经过身份验证,但是当我向 Google Maps API 发送 AJAX 调用时,用户令牌也会被发送。这是我现在设置的代码。

在我的 api js 文件中,该文件首先在页面加载时运行

var token = $('#api-token').val();
$.ajaxSetup({
  headers:{
    "accept": "application/json",
    "token": token
  }
});
Run Code Online (Sandbox Code Playgroud)

在我的 users_controller.rb 中

def profile
    authorize!
    @user = current_user
    @bathrooms = Bathroom.all.sort_by { |name| name }
    render layout: 'profile_layout'
end


def authorize!
  redirect_to '/login' unless current_user
end

def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end
Run Code Online (Sandbox Code Playgroud)

这是我的 AJAX 调用

 function getInfo(location) {
  console.log('getInfo');
  $.ajax({
    method: 'get',
    url: 'https://maps.googleapis.com/maps/api/geocode/json',
    data:{address: location, key: 'API KEY GOES HERE'},
    success: function(data) {
      extractData(data);
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

vij*_*ayP 5

您可以尝试以下步骤:

function getInfo(location) {
  console.log('getInfo');

  delete $.ajaxSettings.headers["token"]; // Remove header before call

  $.ajax({
    method: 'get',
    url: 'https://maps.googleapis.com/maps/api/geocode/json',
    data:{address: location, key: 'API KEY GOES HERE'},
    success: function(data) {
      extractData(data);
    }
  });

  $.ajaxSettings.headers["token"] = token; // Add it back immediately
}
Run Code Online (Sandbox Code Playgroud)