【发布时间】:2019-02-16 06:10:43
【问题描述】:
我在获取函数时遇到以下问题: 反应代码:
componentDidMount() {
this.userService.getLoggedInUser()
.then(user => {
this.setState({user: user});
console.log(this.state.user);
})
}
此课程服务文件代码:
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)
});
}
我只是想从服务器获取登录用户。在使用邮递员做同样的事情时,我得到了预期的输出。 服务器代码:
@PostMapping("/api/loggedInUser")
public Faculty getLoggedInUser(HttpSession session){
return (Faculty)session.getAttribute("currentUser");
}
服务器中的类定义为:
@RestController
@CrossOrigin(origins = "http://localhost:3000", allowCredentials ="true")
public class UserService {
在邮递员中,我得到以下输出:
{
"id": 100,
"username": "bird",
"password": "bird",
"firstName": "Alice",
"lastName": "Kathie"
}
但在反应应用程序中,我进入控制台是:
Response {type: "cors", url: "http://localhost:8080/api/profile", redirected: false, status: 200, ok: true, …}
但是没有要返回或解析的数据体。我不确定我在这里做错了什么。我尝试将 fetch 中的 then 方法更改为各种类型,例如 response.clone().json() 等,但是在大多数情况下,我得到的输出是“承诺被拒绝,json 输入意外结束”。 我怎么解决这个问题? 谢谢
【问题讨论】:
-
你可能想检查一下这个解决方案,看看它是否有帮助:stackoverflow.com/a/43547095/3550662
-
我检查了解决方案,但在网络类型中找不到与标头相关的任何内容。另外,我只开发了api,如何在java后端服务器的代码中添加解决方案中提到的那些行?
标签: javascript reactjs