JQuery.ajax는 C # 서버의 응답을 기다리지 않고 로컬 호스트에서 테스트하는 오류 함수를 호출합니다.

눈사람

사용자 측 , 나는 JQuery.ajax를 통해 서버에이 게시하는 자바 스크립트 코드가 있습니다. 서버 측 , I는 요청을 받고이를 처리되지만 사용자 측 스크립트는 서버 응답 및 통화 대기하지 않는 오류 : getFail (아래 참조) 기능을.

편집 : 문제는 서버와 사용자 측이 다른 도메인, 내 경우에는 다른 로컬 호스트로 인해 발생했습니다. 아래 @Jacob의 자세한 답변을 참조하십시오.

사용자 측이 서버를 기다리는 지 여부를 어떻게 확인 했습니까?
디버그 모드에서 서버를 실행 하고 POST-ed 값을받는 중단 점을 설정했습니다 . 그리고 사용자 측은 이미 오류 함수를 호출했습니다.

  • 아무도 "올바르게"작동하지 않는 이유 또는 오류의 원인이 무엇인지, 어디에 있는지 말해 줄 수 있습니까?

내가 것으로 의심 하나은 "부적절한"행동의 근원은 은 IS 데이터 형식 매개 변수 JQuery.ajax 기능. 서버에서 반환되는 값의 예상 유형을 지정해야합니다. 무엇을 설정해야할지 모르겠으므로 기본값이 알아 내길 바라는 것을 지정하지 않았습니다.

[dataType 매개 변수의 경우 ] 아무것도 지정하지 않으면 jQuery는 응답의 MIME 유형에 따라 추론을 시도합니다. 가능한 유형은 xml, html, script, json, jsonp, text, multiple입니다. (출처 : http://api.jquery.com/jQuery.ajax/ , JQuery 문서).


코드는 다음과 같습니다.

사용자측 자바 스크립트 코드 :

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);
    }
}
Jacob

실제 오류가 무엇인지 확인하면 이것을 확인 / 반증하지만 CORS 문제를 탓하는 것을 보았습니다. 호출이 수행되는 방식과 서버가 지원하는 내용에 따라 전체 요청 인 것처럼 서버에서 처리하는 프리 플라이트 요청이있을 수 있으며, 클라이언트 는 출처 간이 아니기 때문에 응답을 거부 할 수 있습니다. 인정 받은.

서버 측 프레임 워크가 무엇인지 잘 모르겠지만 실제로 이것이 교차 출처 문제인 경우 도움이 될 수 있습니다.

XmlHttpRequest 용 WebAPI를 사용하는 CORS

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관