JQuery.ajax不等待C#Server的响应并调用错误函数,在localhost上进行测试

时间:2015-07-31 23:31:31

标签: c# jquery ajax owin

用户端上,我有一个javascript代码,通过JQuery.ajax POST到服务器。在服务器端,我收到请求并处理它,但是用户端脚本不等待服务器响应并调用错误:getFail (见下文)功能。

编辑:问题是由于服务器和用户端在不同的域上,在我的情况下是不同的localhosts。请参阅下面@Jacob的详细答案。

我如何检查用户端是否等待服务器?
我只是在调试模式下运行服务器,并设置断点,它接收POST-ed值。并且用户端已经调用了错误函数。

  • 有人可以告诉我,为什么它不能正常工作或错误的来源是什么?在哪里?

我怀疑一个 “不正当”行为的来源是JQuery.ajax函数的 dataType参数。它应该指定服务器返回值的预期类型。我不知道该怎么设置这个,所以我没有指定希望默认会找到。

  

[对于dataType参数] 如果未指定,jQuery将尝试根据响应的MIME类型推断它。可能的类型有:xml,html,script,json,jsonp,text,multiple。 (来源:http://api.jquery.com/jQuery.ajax/,JQuery文档)。

以下是代码:

用户端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);
    }
}

1 个答案:

答案 0 :(得分:1)

看到你回来的实际错误将证实/反驳这一点,但我已经看到CORS问题应该归咎于此。根据呼叫的方式和服务器支持的内容,您可能有一个由服务器处理的预检请求,就好像它是完整请求一样,然后客户端可以拒绝响应,因为它不是跨领域授权的。

我不确定您的服务器端框架是什么,但如果确实这是一个跨域问题,这可能会有所帮助:

CORS with WebAPI for XmlHttpRequest