gpt4 book ai didi

javascript - 从 fetch 请求中提取数据并将其导出

转载 作者:行者123 更新时间:2023-12-03 14:36:54 26 4
gpt4 key购买 nike

我很高兴加入 StackOverFlow 社区。
我是 Web 开发的新手,有数十亿个问题。
我的问题将涉及 javascript 中的获取请求。
我正在尝试从响应中提取数据(userId)以便将其导出,但我不能。
我试图将 userId 变量设置为全局,但它不起作用。
有没有人可以在这个问题上帮助他。
预先感谢您的回答。

let userId = "";

let loggedUserId = () => {
let storageToken = localStorage.getItem("groupomania");
let objJson = JSON.parse(storageToken);
let token = objJson.token;

let params = token;

const headers = new Headers();
headers.append("Authorization", `Bearer ${token}`);

let url = "http://localhost:3000/api/user/userId/" + params;

const parametresDeRequete = {
method: "GET",
headers: headers,
};

fetch(url, parametresDeRequete)
.then(function(response) {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
return;
}

response.json().then(function(data) {
userId = data.data;

console.log(
"%c ⚠️ Utilities Logged User Id ⚠️ ===>>",
"color:red ; font-size: 15px",
userId
);
});
})

.catch(function(err) {
console.log("Fetch Error :-S", err);
});
};

loggedUserId();

最佳答案

你需要先返回 response.json() 。然后你将另一个链接到你接收数据的那个(如果有的话)。确保您收到的数据是 json。

fetch(url, parametresDeRequete)
.then(function(response) {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
return;
} else {
return response.json(); // returns unresolved Promise
}
}
.then(function(data) { // data refers to the resolved promise. If the response is not json then the previous .json() method will throw an error which you will be able to catch with .catch()
userId = data.id;

console.log(
"%c ⚠️ Utilities Logged User Id ⚠️ ===>>",
"color:red ; font-size: 15px",
userId
);
});
})
.catch(function(err) {
console.log("Fetch Error :-S", err);
});

关于javascript - 从 fetch 请求中提取数据并将其导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66881742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com