gpt4 book ai didi

javascript - 即使在react中状态为200,也无法在fetch中获取数据

转载 作者:行者123 更新时间:2023-12-03 00:11:34 25 4
gpt4 key购买 nike

我在获取函数时遇到以下问题: react 代码:

 componentDidMount() {
this.userService.getLoggedInUser()
.then(user => {
this.setState({user: user});
console.log(this.state.user);
})
}

这是类(class)服务文件代码:

getLoggedInUser(){
const USER_API_URL = API_URL + "/api/profile";
return fetch(USER_API_URL, {
headers : {
'Content-Type' : 'application/json'
},
method : "POST"
}).then(response => response.clone()).then(data => {
console.log(data);
return data;
}).catch(function (err) {
console.log(err)
});
}

我只是想从服务器获取登录用户。在使用 postman 执行相同操作时,我得到了预期的输出。服务器代码:

@PostMapping("/api/loggedInUser")
public Faculty getLoggedInUser(HttpSession session){
return (Faculty)session.getAttribute("currentUser");
}

服务器中的类定义为:

@RestController
@CrossOrigin(origins = "http://localhost:3000", allowCredentials ="true")
public class UserService {

在 postman 中,我得到以下输出:

{
"id": 100,
"username": "bird",
"password": "bird",
"firstName": "Alice",
"lastName": "Kathie"
}

但是在 react 应用程序中,我进入控制台的方式为:

Response {type: "cors", url: "http://localhost:8080/api/profile", redirected: false, status: 200, ok: true, …}

但是没有数据体可供返回或解析。我不确定我在这里做错了什么。我尝试将 fetch 中的 then 方法更改为各种类型,例如 response.clone().json() 等,但是在大多数情况下,我得到的输出为“promise returned,unexpected end of json input”。我怎么解决这个问题?谢谢

最佳答案

看起来错误在于您处理回复的方式:

 }).then(response => response.clone()).then(data => {

第二个 .then() 中的数据不返回提取响应,而是返回提取本身的详细信息。在 .then(response => 中,您可能想要执行以下操作:

.then(response => {
return response.json()
}

目前尚不清楚您想用response.clone()做什么,因为这通常会创建响应的克隆以用于缓存或其他东西——您想用克隆做什么?

如果您在缓存函数中使用它,也许您可​​以:

.then(response => {
someCacheFunction(response.clone())
return response.json()
}

或者如果您将其设置为预定义变量以供某些用途:

var responseClone;
... // code omitted
.then(response => {
responseClone = response.clone()
return response.json()
}

关于javascript - 即使在react中状态为200,也无法在fetch中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54702370/

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