Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 无法分析以获取令牌_Node.js_Reactjs_Express - Fatal编程技术网

Node.js 无法分析以获取令牌

Node.js 无法分析以获取令牌,node.js,reactjs,express,Node.js,Reactjs,Express,出于某种原因,我无法从localstorage获取令牌以发出请求,它表示没有令牌。我正在使用cookie解析器。我正在尝试为我的店铺创建一个新类别。它没有识别令牌,尽管它在这里 这是我的客户: adminDashoard.js import { useState } from 'react'; import { createCategory } from './api/category'; import isEmpty from 'validator/lib/isEmpty'; import {

出于某种原因,我无法从localstorage获取令牌以发出请求,它表示没有令牌。我正在使用cookie解析器。我正在尝试为我的店铺创建一个新类别。它没有识别令牌,尽管它在这里

这是我的客户:

adminDashoard.js

import { useState } from 'react';
import { createCategory } from './api/category';
import isEmpty from 'validator/lib/isEmpty';
import { showErrorMsg, showSuccessMsg } from './helpers/message';
import { showLoading } from './helpers/Loading'



export default function AdminDashboard() {
const [category, setCategory] = useState('');
const [errorMsg, setErrorMsg] = useState('');
const [successMsg, setSuccessMsg] = useState('');
const [loading, setLoading] = useState(false);

const handleMessages= evt =>{
    setErrorMsg('');
    setSuccessMsg('');
}

const handleCategoryChange = (evt) => {
    setErrorMsg('');
    setSuccessMsg('');
    setCategory(evt.target.value);
   

}
const handleCategorySubmit = (evt) => {
    evt.preventDefault();



    if (isEmpty(category)) {

        setErrorMsg('Please enter a category')
    } else {
        const data = { category }

        setLoading(true);
        createCategory(data)
            .then(response => {
                setLoading(false);
                setSuccessMsg(response.data.successMessage)
            })
            .catch(err => {
                setLoading(false);
                setErrorMsg(err.response.data.errorMessage)
                console.log(err)
            })

    }


};



function ShowHeader() {
    return (
        <div className='bg-dark text-white py-4'>
            <div className='container'>
                <div className='row'>
                    <div className='col-md-6'>
                        <h1>
                            <i className='fas fa-home'>   Dashboard</i>
                        </h1>

                    </div>
                </div>
            </div>
        </div>
    )
}

function ShowActionBtns() {
    return (
        <div className='bg-light my-2'>
            <div className='container'>
                <div className='row pb-3'>
                    <div className='col-md-4 my-1 '>
                        <button
                            className='btn btn-outline-info btn-block'
                            data-toggle='modal'
                            data-target='#addCategoryModal'>
                            <i className=' fas fa-plus'>Add Category</i>
                        </button>
                    </div>
                    <div className='col-md-4 my-1 '>
                        <button className='btn btn-outline-danger btn-block'>
                            <i className=' fas fa-plus'>Add Products</i>
                        </button>
                    </div>
                    <div className='col-md-4 my-1 '>
                        <button className='btn btn-outline-success btn-block'>
                            <i className=' fas fa-plus'>Add Blog</i>
                        </button>
                    </div>

                </div>

            </div>

        </div>
    )
}

function ShowCategoryModal() {
    return (
        <div id='addCategoryModal' className='modal' onClick={handleMessages}>
            <div className='modal-dialog modal-dialog-centered modal-lg'>
                <div className='modal-content'>
                    <form onSubmit={handleCategorySubmit}>

                        <div className='modal-header bg-info text-white'>
                            <h5 className='modal-title'>Add Category</h5>
                            <button className='close' data-dismiss='modal'>
                                <span>
                                    <i className='fas fa-times'></i>
                                </span>
                            </button>
                        </div>

                        <div className='modal-body my-2'>
                            {errorMsg && showErrorMsg(errorMsg)}
                            {successMsg && showSuccessMsg(successMsg)}
                            {
                                loading ? (
                                    <div className='text-center'>{showLoading()}</div>
                                ) : (
                                    <>
                                        <label className='text-secondary'> Category</label>
                                        <input
                                            type='text'
                                            className='form-control'
                                            name='category'
                                            value={category}
                                            onChange={handleCategoryChange}
                                        />
                                    </>
                                )
                            }


                        </div>

                        <div className='modal-footer'>
                            <button data-dismiss='modal' className='btn btn-secondary'>Close</button>
                            <button className='btn btn-info' type='submit'>Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    )
}

return <div>
    {ShowHeader()}
    {ShowActionBtns()}
    {ShowCategoryModal()}
</div>
    }
}

在服务器端

  here is my server.js : 
  const express=require('express');
  const app= express();
  const cors=require('cors');
  const connectDB= require('./database/db');
  const morgan= require('morgan');
  const authRoutes= require ('./routes/auth')
  const categoryRoutes = require ('./routes/category');
  const cookieParser = require('cookie-parser')

  //middleware
  app.use(cors());
  app.use(morgan('dev'));
  app.use(express.json());
  app.use(cookieParser());
  app.use('/api/auth', authRoutes);
  app.use('/api/category', categoryRoutes);

  connectDB();

  const port = process.env.PORT || 5000;

  app.listen(port, () => console.log(`Listening on port ${port}`));

  app.get('/', (req, res) =>{
  res.send(' hello server')
    })
这是我的路线文件:

  const express = require('express');
  const router = express.Router();
  const categoryController = require('../routes/controllers/category');
  const  {authenticatateJWT} = require('./middleware/authenticator');

  router.post('/', authenticatateJWT, categoryController.create);

  module.exports = router;
这是我的控制器:

    exports.create = (req, res)=>{
    console.log(req.user);

    setTimeout(() =>{
    res.json({
      successMessage: `${req.body.category} was created!`
      });
      }, 5000)

      }
这是我的中间件:

    const jwt = require('jsonwebtoken');
    const { jwtSecret } = require('../../config/keys');

    exports.authenticatateJWT = (req, res, next) => {
     const token = req.cookies.token;
     console.log(token);
     if (!token) {
     return res.status(401).json({
        errorMessage: 'No token. Authorization denied',
       });
    }
       try {
       const decoded = jwt.verify(token, jwtSecret);

       req.user = decoded.user;
       next();
        } catch (err) {
          console.log('jwt error:', err)
          res.status(401).json({
          errorMessage: 'Invalid token',

          });
      }
    };

您提到了localstorage,但代码使用cookie。此外,您发布的代码中没有将令牌发送到客户端的位置。客户端从哪里获得令牌?实际上令牌存储在本地存储中,我有一个单独的文件。我得到这个错误“uncaught(in promise)TypeError:err.response是未定义的handleCategorySubmit AdminDashboard.js:38”。
    const jwt = require('jsonwebtoken');
    const { jwtSecret } = require('../../config/keys');

    exports.authenticatateJWT = (req, res, next) => {
     const token = req.cookies.token;
     console.log(token);
     if (!token) {
     return res.status(401).json({
        errorMessage: 'No token. Authorization denied',
       });
    }
       try {
       const decoded = jwt.verify(token, jwtSecret);

       req.user = decoded.user;
       next();
        } catch (err) {
          console.log('jwt error:', err)
          res.status(401).json({
          errorMessage: 'Invalid token',

          });
      }
    };