[英]POST-request to get data from API
我正在嘗試為我的 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 正文發送到后端,后端確實返回響應,但前端似乎無法處理所述響應。 我想知道出了什么問題; 當我調試我的代碼從 first.then 一直到最后,跳過 rest。
像這樣?
$.ajax({
type : "POST",
url : "http://localhost/service.asp",
data: {Email: "asd@asd.asd", Password: "asdasd"},
//data: '{Email: "asd@asd.asd", Password: "asdasd"}',
headers : {
"Accept" : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
}
success : function(response) {
Console.log(response);
}
});
我看到的是您使用的是大寫鍵,但在您的 postman 中,我可以看到所有鍵都是小寫的。 您使用了帶有大寫 T 的response.Token之類的鍵。但是您從 postman 的響應似乎就像帶有小 t 的response.token 。 除此之外,您的代碼也有一些類型錯誤。 您在 accessPass 變量中的響應拼寫錯誤。
您的 function 需要像:-
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: response.token,
User:
{
Email: response.user.email,
Type: response.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);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.