-2

Below is my protect route, which uses the jwt token to verify the user. I have tested the route using Postman and I receive the id, name which is correct. What I am trying to achieve is send a GET request using Fetch API to get this data and display it on my Profile component which I found on the react docs. I have also included how I have tried however all suggestions are welcome.

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

/me route

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);

  });
});

Profile Component

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;
John
  • 171
  • 3
  • 19
  • What happens? Look at the developer tools in your browser. Look at the Console. Are any error messages reported? Look at the Network tab. Do you see the request? Is it formatted as you expect? Does it get a response? Is it formatted as you expect? – Quentin Jul 14 '19 at 20:32
  • Betting this is yet another duplicate of https://stackoverflow.com/a/35553666/19068 – Quentin Jul 14 '19 at 20:32
  • @Quentin what do you suggest thats a lot of info lol – John Jul 14 '19 at 20:34
  • I will answer your questions soon , when I am back at my laptop – John Jul 14 '19 at 20:34

1 Answers1

0

You need to send x-acess-token with api request as it is protected route :

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
    //  /   });
Shubham Verma
  • 4,918
  • 1
  • 9
  • 22
  • Thanks. I shall try this. also how do I add my token in the x-access-token field? since i'm already verifying my token in my /me api route? also I might have to use localStorage for this application – John Jul 14 '19 at 20:56
  • You need some way like when you login you should return token which should be stored in ```localstorage(eg localstore.set('Your token')) ``` or any storage and then when you call another jwt api you need to append that token with your api(i.e by fetching it from storage e.g ```localstore.get('Your token')```). – Shubham Verma Jul 15 '19 at 06:50