【发布时间】:2016-01-01 18:45:22
【问题描述】:
我正在尝试创建基本身份验证页面,其中我的表单具有三个字段
- 用户名
- 密码
- 授权类型
在提交表单时,我只想在我的 HTML 上以 JSON 格式显示来自服务器的返回响应。 我对 Web 服务的 AJAX 调用还需要设置 Authorization 标头。 但不知何故,标题没有设置。我正在尝试
beforeSend : function(xhr)
{
xhr.setRequestHeader('Authorization', "Basic ******");
xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
}
但是当我在控制台中调试代码时,似乎断点永远不会进入这个函数。 我是 Ajax 的新手,并通过在互联网上搜索来尝试以下代码。 我在下面发布整个代码。
代码:
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
var formData = {
'username': $('#username').val(),
'password': $('#password').val(),
'grant_type': $('#grantType').val()
};
// process the form
$.ajax({
type : 'POST',
url : 'http://localhost:9090/oauth/token',
beforeSend: function (xhr)
{
xhr.setRequestHeader("Authorization", "Basic ******");
xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
},
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
alert(data);
// here we will handle errors and validation messages
})
.fail(function (jqXHR, textStatus){
alert('Status : ' + textStatus + '' + JSON.stringify(jqXHR));
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
导致我的代码中没有设置标题的原因。 请纠正我。
在“网络”选项卡的控制台(Google Chrome)中,我可以看到下面的请求标头
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type, contenttype
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.1.128:9090
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
当从 Google Chrome 的 Advanced Rest Client 扩展程序调用相同的 API 时,它会显示所有标题
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
contentType: application/json;charset=UTF-8
Authorization: Basic **********
Content-Type: application/x-www-form-urlencoded
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
我只是使用 file 协议运行我的网页。
例如:file:///E:/Mahendra/Practice%20Example/Test/OauthTest.html
我不确定这是否会导致问题。
【问题讨论】:
-
这似乎是一个 CORS 问题,跨域请求被阻止,stackoverflow.com/questions/5750696/…
标签: javascript jquery ajax request-headers