如何从提取API调用返回数据?

时间:2019-07-14 20:29:56

标签: node.js reactjs fetch-api

下面是我的保护路线,该路线使用jwt令牌来验证用户。我已经使用邮递员测试了该路线,并且收到了ID(正确的名称)。我想要实现的是使用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;

1 个答案:

答案 0 :(得分:0)

您需要通过api请求发送x-acess-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
    //  /   });