POST请求以从API获取数据

问题描述 投票:0回答:1

我正在尝试为我的API创建一个登录系统,但似乎无法在Javascript代码中得到响应。但是,在POSTman中,我可以:

https://i.stack.imgur.com/WneNm.png

这是我的JavaScript代码:

function loginUser(email, password) {
    let person = {Email: email, Password: password};
    fetch(UrlAuthenticationToken, {
        method: "POST",
        body: JSON.stringify(person),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
        .then((response) =>{
            if (response.status === 200) {
                console.log(`Logged in ${response.status}`);
                return response.json(); // only for generating token
            } else {
                throw new Error(`error with status ${response.status}`);
            }
        })
        .then((response) => {

            let accessPass =
            {
                Token: reponse.Token,
                User:
                {
                    Email: reponse.User.Email,
                    Type: reponse.User.Type
                }
            }

            sessionStorage.setItem(accessPass);

            if(response.User.Type === 'Student'){
                window.href(UrlStudent);
            }
            else if(response.User.Type === 'Lector'){
                window.href(UrlLecturer)
            }
            else if(response.User.Type === 'Business'){
                window.href(UrlCompany)
            }
        })
        .catch((e) => {
            Console.log(e);
        });
};

事实是,我可以将JSON正文发送到后端,而后端确实返回响应,但是前端似乎无法处理所述响应。我不知道出什么事了;当我调试时,我的代码从第一个开始,然后一直到最后,跳过其余部分。

javascript c# post fetch webapi
1个回答
0
投票

喜欢这个?

$.ajax({
  type : "POST",
  url : "http://localhost/service.asp",
  headers : {          
    "Accept" : "application/json; charset=utf-8",         
    "Content-Type": "application/json; charset=utf-8"   
  }        
  success : function(response) {  
    Console.log(response);
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.