【问题标题】:Not getting data in fetch even if the status is 200 in react即使状态为 200 也无法获取数据
【发布时间】: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


【解决方案1】:

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

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

第二个 .then() 中的数据没有返回 fetch 响应,而是返回 fetch 本身的详细信息。在.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()
}

【讨论】:

  • 如果我不克隆,我会收到以下错误:“Promise {: SyntaxError: Unexpected end of JSON input”和“Failed to execute 'json' on 'Response': body流被锁定”
  • 你能帮忙吗
  • 怎么样` .then(response => { return response.json() } ).then( myJson => { return JSON.stringify(myJson) } )` 另外,你能分享一下你的得到你的 console.log 响应,如 response => { console.log(response) } ?
  • 我得到以下日志“esponsebody: (...)bodyUsed: trueheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: ""type: "cors"url: "localhost:8080/api/profile" proto: 响应 webpack-internal:///./src/services/UserService.js:33 SyntaxError: eval 处 JSON 输入意外结束 (webpack-internal:///./src/services /UserService.js:28) webpack-internal:///./src/components/WhiteBoard.js:104 未定义 webpack-internal:///./src/components/WhiteBoard.js:110 未定义"
【解决方案2】:

找到了答案。主要问题是饼干。在获取时,我们需要确保设置了以下内容:

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

"credentials":"include" 是必需的,以便浏览器接受 cookie 并使用相同的 cookie 从服务器检索数据。

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多