簡體   English   中英

如何從 fetch api 調用中返回數據?

[英]How to return data from an fetch api call?

下面是我的保護路由,它使用 jwt 令牌來驗證用戶。 我已經使用 Postman 測試了路線,並且收到了正確的 id 和 name。 我想要實現的是使用 Fetch API 發送 GET 請求以獲取此數據並將其顯示在我在 react 文檔中找到的 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;

您需要使用 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
    //  /   });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM