【问题标题】:How to return data from an fetch api call?如何从 fetch api 调用中返回数据?
【发布时间】:2019-11-23 15:16:32
【问题描述】:

下面是我的保护路由,它使用 jwt 令牌来验证用户。我已经使用 Postman 测试了路线,我收到了正确的 id,名称。我想要实现的是使用 Fetch API 发送一个 GET 请求以获取此数据并将其显示在我在反应文档中找到的 Profile 组件上。我还包括了我的尝试方法,但欢迎所有建议。

{
    "id": 8,
    "name": "Kie",
    "iat": 1563135959,
    "exp": 1563137399
}

/我的路线

router.get('/me', function(req, res) {
  var token = req.headers['x-access-token'];
  if (!token)
    return res.status(401).send({ auth: false, message: 'No token provided.' });

  jwt.verify(token, secret, function(err, decoded) {
    if (err)
      return res
        .status(500)
        .send({ auth: false, message: 'Failed to authenticate token.' });

    res.status(200).send(decoded);

  });
});

配置文件组件

import React, { Component } from 'react';
import jwt_decode from 'jwt-decode';


class Profile extends Component {
  constructor() {
    super();
    this.state = {
      Items: [],
      hasErrored: false,
      isLoading: false
    };
  }

  componentDidMount() {
    fetch('http://localhost:5000/api/me')
      .then(response => {
        if (!response.ok) {
          throw response;
        } // Return the complete error response for debugging purposes
        return response.json(); //we only get here if there is no error
      })
      .then(json => {
        this.setState({ Items: json.Items });
      });
    // .catch(error => {
    // () => this.setState({ hasErrored: true, error }); // Save both error flag and error detail so you can send it to tools like bugsnag
    //  /   });
  }

  render() {
    // if (this.state.hasErrored) {
    //   return <p>There was an error loading the items</p>;
    // }
    if (this.state.isLoading) {
      return <p>Loading...</p>;
    }

    return (
      <div>
        <ul>
          {this.state.Items.map(item => (
            <li key={item.ID}></li>
          ))}
        </ul>
      </div>
    );
  }
}

export default Profile;

【问题讨论】:

  • 会发生什么?查看浏览器中的开发人员工具。查看控制台。是否报告了任何错误消息?查看网络选项卡。你看到请求了吗?它的格式是否符合您的预期?它得到回应了吗?它的格式是否符合您的预期?
  • 赌这是stackoverflow.com/a/35553666/19068的另一个副本
  • @Quentin 你有什么建议这么多信息哈哈
  • 当我回到我的笔记本电脑时,我会尽快回答你的问题

标签: node.js reactjs fetch-api


【解决方案1】:

您需要通过 api 请求发送 x-access-token,因为它是受保护的路由:

fetch('http://localhost:5000/api/me', { 
   method: 'get', 
    headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'x-access-token' : "Your Token" // you need to add your token

  }, 
 })
.then(response => {
        if (!response.ok) {
          throw response;
        } // Return the complete error response for debugging purposes
        return response.json(); //we only get here if there is no error
      })
      .then(json => {
        this.setState({ Items: json.Items });
      });
    // .catch(error => {
    // () => this.setState({ hasErrored: true, error }); // Save both error flag and error detail so you can send it to tools like bugsnag
    //  /   });

【讨论】:

  • 谢谢。我要试试这个。另外如何在 x-access-token 字段中添加我的令牌?因为我已经在 /me api 路由中验证了我的令牌?我也可能必须为此应用程序使用 localStorage
  • 您需要某种方式,例如登录时应返回令牌,该令牌应存储在 localstorage(eg localstore.set('Your token')) 或任何存储中,然后当您调用另一个 jwt api 时,您需要将该令牌附加到您的 api 中(即通过从存储中获取它,例如localstore.get('Your token'))。
猜你喜欢
  • 2021-11-22
  • 1970-01-01
  • 2017-09-05
  • 2017-09-13
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
相关资源
最近更新 更多