“指定了无效的令牌:无法读取未定义的属性“替换”

时间:2019-11-04 21:34:10

标签: javascript reactjs express axios

我正在开发一个应用程序,在该应用程序中,我可以让用户进行身份验证并也可以授权我通过后端将令牌成功发送到客户端,但是在

时出现此错误

错误:books:1(承诺中)InvalidTokenError。{消息:“指定的无效令牌:无法读取未定义的属性'replace'”} 我检查了网站https://jwt.io/中的令牌,但签名无效,所以我想为什么会这样,但我却忽略了解决方法

前端

import axios from 'axios'

export const register = newUser => {
  return axios
    .post('users/register', {
      first_name: newUser.first_name,
      last_name: newUser.last_name,
      email: newUser.email,
      password: newUser.password
    })
    .then(response => {
      console.log('Registered')
    })
}

export const login = user => {
  return axios
    .post('http://localhost:5001/login', {
      name: user.name,
      password: user.password
    })
    .then(response => {

      localStorage.setItem('usertoken', response.data)
      return response.data

    })
    .catch(err => {
      console.log(err)
    })
}


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

class Profile extends Component {
  constructor() {
    super()
    this.state = {
      first_name: '',
      errors: {}
    }
  }

  componentDidMount() {
    const token = localStorage.usertoken
    const decoded = jwt_decode(token)
    this.setState({
      first_name: decoded.name,

    })
  }

  render() {
    return (
      <div className="container">
        <div className="jumbotron mt-5">
          <div className="col-sm-8 mx-auto">
            <h1 className="text-center">PROFILE</h1>
          </div>
          <table className="table col-md-6 mx-auto">
            <tbody>
              <tr>
                <td>Fist Name</td>
                <td>{this.state.first_name}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    )
  }
}

export default Profile

后端app.js

const express = require('express')
var cookieParser = require('cookie-parser')
const app = express()
var cors = require('cors')
var bodyParser = require('body-parser')
const port = 5000
const routes = require("./routes");
const con = require('./db')
var cors = require('cors')
app.use(cors())
// database connect 

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
  });

  //cookie 
  app.use(cookieParser())
//routes
// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

app.use("/", routes);


app.listen(port, () => console.log(`Example app listening on port ${port}!`))
here is routes

var express = require('express')
var router = express.Router()
var Controller = require('./controller')
var authController = require('./authController')
var BooksIdeaController = require('./BooksIdeaController')
router.post('/register',Controller.register);
router.post('/login',authController.login);
router.post('/booksIdea/:id',authController.verify,BooksIdeaController.addComment)
router.post('/booksIdea/addbook',authController.verify,BooksIdeaController.addBookIdea)
router.get('/booksIdea/show',authController.verify,BooksIdeaController.showBookIdea)
router.put('/booksIdea/edit/:id',authController.verify,BooksIdeaController.UpdateBookIdea)
router.delete('/booksIdea/delete/:id',authController.verify,BooksIdeaController.DeleteBookIdea)
module.exports = router;

const con = require('./db');
var bcrypt = require('bcrypt');
let jwt = require('jsonwebtoken');
const express = require('express')
var cookieParser = require('cookie-parser')
const app = express()
module.exports.login=function(req,res){
    var username=req.body.name;
    var password=req.body.password;
    con.query('SELECT * FROM users WHERE username = ?',[username], function (error, results, fields) {
      if (error) {
          res.json({
            status:false,
            message:'there are some error with query'
            })
      }else{
        if(results.length >0){
          bcrypt.compare(password, results[0].password, function (err, result) {
            if (result == true) {
        jwt.sign({user:results},'configSecret',(err,token)=>{
          // res.json({
          //   token:token
          // })
          res.json({
            token,

          })

        });



            //   res.json({
            //     status:true,
            //     message:'successfully authenticated'
            // })
            } else {
              res.json({
                      status:false,
                      message:"username and password does not match"
                     });
            }
          });
        }
        else{
          res.json({
              status:false,    
            message:"username does not exits"
          });
        }
      }
    });
}

module.exports.home=function(req,res){
res.send('hello');
}
//////
// if(password==results[0].password){

  // }else{
  //    
  // }
  module.exports.verify = function verifyToken(req, res, next) {
    // Get auth header value
    const bearerHeader = req.headers['authorization'];
    // Check if bearer is undefined
    if(typeof bearerHeader !== 'undefined') {
      // Split at the space
      const bearer = bearerHeader.split(' ');
      // Get token from array
      const bearerToken = bearer[1];
      // Set the token
      req.token = bearerToken;
      // Next middleware
      next();
    } else {
      // Forbidden
      res.sendStatus(403);
    }

  }

0 个答案:

没有答案