我这里有一个非常奇怪的问题,我认为这与 Backbone.js 路由有关。
在我们的移动应用程序中,有一个登录屏幕,它执行针对 API 运行的 AJAX-Post-Request(使用 jQuery)。用户名、密码和第三个参数位于 POST 正文中。这就像一个魅力。
在 Backbone.js 开始执行一些路由之后,奇怪的行为开始出现。重定向浏览器后,(仅!)用户名和密码作为参数列表发送到 GET 请求。
所以请求即
http://localhost:3000/#login
由于未知原因变成
http://localhost:3000/?username=myuser&password=mypassword#login
请注意,GET 请求中的新参数并不是 100% POST 正文的一部分,因为缺少 savePassword 参数。另请注意,登录请求违反 API (/api/user/login),而不是登录屏幕的路线 (/#login)
我已经尝试了很多东西,也将所有主干源代码分开,但仍然找不到如何防止这种行为。
另一个注意事项:我只在移动设备上看到这个,所以在 iOS 上的 UIWebView 和 Android 上的 WebView 对象中。也许这个问题也与移动设备有关......
我非常高兴获得任何帮助、答案或提示,以及如何禁用此行为并从这个奇怪的 URL 中获取用户名/密码。
编辑: 这是登录的 AJAX 请求。
login: function(username, password, savePassword, successcallback, errorcallback) {
$.ajax({
method: 'POST',
dataType: 'json',
url: config.api_base_url + 'user/login',
data: {
username: username,
password: password,
savePassword: savePassword
},
success: function(data, response, xhr) {
app.auth_token = xhr.getResponseHeader('Authtoken');
$.cookie('auth_token', app.auth_token);
if (successcallback) {
successcallback();
}
},
error: function(data) {
if (errorcallback) {
errorcallback(data);
}
}
});
}
最佳答案
根据jQuery.ajax()文档:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
然后,您应该在设置中添加 processData
等于 false:
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
代码 jQuery.ajax():
login: function(username, password, savePassword, successcallback, errorcallback) {
$.ajax({
method: 'POST',
dataType: 'json',
url: config.api_base_url + 'user/login',
data: {
username: username,
password: password,
savePassword: savePassword
},
processData: false,
success: function(data, response, xhr) {
app.auth_token = xhr.getResponseHeader('Authtoken');
$.cookie('auth_token', app.auth_token);
if (successcallback) {
successcallback();
}
},
error: function(data) {
if (errorcallback) {
errorcallback(data);
}
}
});
}
关于javascript - 如何防止 Backbone.js 路由(或历史记录)自动向 GET 请求添加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530017/