JQuery.ajax 不等待 C# 服务器的响应并调用错误函数,在本地主机上测试
JQuery.ajax does not wait for C# Server's response and calls error function, testing on localhost
在用户端,我有一个javascript代码,POST通过JQuery.ajax发送到服务器。在服务器端,我收到请求并处理它,但用户端脚本不等待服务器响应并调用错误:getFail(见下文)函数。
编辑:问题是由于服务器和用户端位于不同的域,在我的例子中是不同的本地主机。请参阅下面@Jacob 的详细回答。
我如何检查用户端是否等待服务器?
我刚刚 运行 服务器处于调试模式,并设置了一个 断点 它接收 POST-ed 值。并且用户端已经调用了错误函数。
- 谁能告诉我,为什么它不起作用 "properly" 或者错误的来源是什么?
我怀疑其中一个 "improper" 行为的来源 是 dataType JQuery.ajax 函数的参数 。它应该指定来自服务器的 return 值的预期类型。我不确定要设置什么,所以我没有指定希望默认值会发现。
[For the dataType parameter] If none is specified, jQuery will try to infer it based on the MIME type of the response. Possible types are: xml, html, script, json, jsonp, text, multiple. (Source: http://api.jquery.com/jQuery.ajax/, JQuery docs).
代码如下:
用户端javascript代码:
function logIn() {
try {
alert('try in logIn');
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: {
"grant_type": "password",
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
},
contentType: "application/x-www-form-urlencoded", // data type sent to server
// dataType: "json", // data type expected from server <- THIS may be a source of the problem
success: getSuccess,
error: getFail
});
} catch (e) {
alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
//jqXHR.status is 0
//textStatus is "error"
//errorThrown is empty
alert(jqXHR.status); // <-- THIS is what gets called, instantly after the post.
};
};
服务器端 C# 代码:
public class ApplicationOAuthServerProvider
: OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
await Task.FromResult(context.Validated()); // break-point was here
}
// This is called by await Task.FromResult(context.Validated())
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
// Here manager will have correct values from the POST-ed data
var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await manager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError(
"invalid_grant", "The user name or password is incorrect.");
context.Rejected();
return;
}
foreach (var userClaim in user.Claims)
{
identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
}
context.Validated(identity);
}
}
看到你返回的实际错误是什么confirm/disprove,但我已经看到 CORS 问题应该归咎于此。根据调用的方式和服务器支持的内容,您可能有一个由服务器处理的预检请求,就好像它是完整请求一样,然后 client 可以拒绝响应,因为它未获得跨域授权。
我不确定你的服务器端框架是什么,但如果这确实是一个跨源问题,这可能会有所帮助:
在用户端,我有一个javascript代码,POST通过JQuery.ajax发送到服务器。在服务器端,我收到请求并处理它,但用户端脚本不等待服务器响应并调用错误:getFail(见下文)函数。
编辑:问题是由于服务器和用户端位于不同的域,在我的例子中是不同的本地主机。请参阅下面@Jacob 的详细回答。
我如何检查用户端是否等待服务器?
我刚刚 运行 服务器处于调试模式,并设置了一个 断点 它接收 POST-ed 值。并且用户端已经调用了错误函数。
- 谁能告诉我,为什么它不起作用 "properly" 或者错误的来源是什么?
我怀疑其中一个 "improper" 行为的来源 是 dataType JQuery.ajax 函数的参数 。它应该指定来自服务器的 return 值的预期类型。我不确定要设置什么,所以我没有指定希望默认值会发现。
[For the dataType parameter] If none is specified, jQuery will try to infer it based on the MIME type of the response. Possible types are: xml, html, script, json, jsonp, text, multiple. (Source: http://api.jquery.com/jQuery.ajax/, JQuery docs).
代码如下:
用户端javascript代码:
function logIn() {
try {
alert('try in logIn');
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: {
"grant_type": "password",
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
},
contentType: "application/x-www-form-urlencoded", // data type sent to server
// dataType: "json", // data type expected from server <- THIS may be a source of the problem
success: getSuccess,
error: getFail
});
} catch (e) {
alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
//jqXHR.status is 0
//textStatus is "error"
//errorThrown is empty
alert(jqXHR.status); // <-- THIS is what gets called, instantly after the post.
};
};
服务器端 C# 代码:
public class ApplicationOAuthServerProvider
: OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
await Task.FromResult(context.Validated()); // break-point was here
}
// This is called by await Task.FromResult(context.Validated())
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
// Here manager will have correct values from the POST-ed data
var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await manager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError(
"invalid_grant", "The user name or password is incorrect.");
context.Rejected();
return;
}
foreach (var userClaim in user.Claims)
{
identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
}
context.Validated(identity);
}
}
看到你返回的实际错误是什么confirm/disprove,但我已经看到 CORS 问题应该归咎于此。根据调用的方式和服务器支持的内容,您可能有一个由服务器处理的预检请求,就好像它是完整请求一样,然后 client 可以拒绝响应,因为它未获得跨域授权。
我不确定你的服务器端框架是什么,但如果这确实是一个跨源问题,这可能会有所帮助: