gpt4 book ai didi

javascript - 如何从单个请求的 AJAX 调用中删除 header ?

转载 作者:行者123 更新时间:2023-11-29 10:11:30 26 4
gpt4 key购买 nike

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

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

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

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

在我的 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

这是我的 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);
}
})
}

最佳答案

您可以尝试以下步骤:

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
}

关于javascript - 如何从单个请求的 AJAX 调用中删除 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com