快递请求抛出401未经授权

问题描述 投票:0回答:1

创建列表的后端路由显示错误。即使在登录并且存在 auth-token 后也会抛出 401(未经授权)。

list.js(路线)

const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const member = require('../middleware/member');
const { check, validationResult } = require('express-validator');

const User = require('../models/User');
const Board = require('../models/Board');
const List = require('../models/List');

router.post(
  '/',
  [auth, member, [check('title', 'Title is required').not().isEmpty()]],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    try {
      const title = req.body.title;
      const boardId = req.header('boardId');

      const newList = new List({ title });
      const list = await newList.save();

      const board = await Board.findById(boardId);
      board.lists.push(list.id);

      const user = await User.findById(req.user.id);
      board.activity.unshift({
        text: `${user.name} added '${title}' to this board`,
      });
      await board.save();

      res.json(list);
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  }
);

router.get('/boardLists/:boardId', auth, async (req, res) => {
  try {
    const board = await Board.findById(req.params.boardId);
    if (!board) {
      return res.status(404).json({ msg: 'Board not found' });
    }

    const lists = [];
    for (const listId of board.lists) {
      lists.push(await List.findById(listId));
    }

    res.json(lists);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

router.get('/:id', auth, async (req, res) => {
  try {
    const list = await List.findById(req.params.id);
    if (!list) {
      return res.status(404).json({ msg: 'List not found' });
    }

    res.json(list);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

router.patch(
  '/rename/:id',
  [auth, member, [check('title', 'Title is required').not().isEmpty()]],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    try {
      const list = await List.findById(req.params.id);
      if (!list) {
        return res.status(404).json({ msg: 'List not found' });
      }

      list.title = req.body.title;
      await list.save();

      res.json(list);
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  }
);

router.patch('/archive/:archive/:id', [auth, member], async (req, res) => {
  try {
    const list = await List.findById(req.params.id);
    if (!list) {
      return res.status(404).json({ msg: 'List not found' });
    }

    list.archived = req.params.archive === 'true';
    await list.save();

    const user = await User.findById(req.user.id);
    const board = await Board.findById(req.header('boardId'));
    board.activity.unshift({
      text: list.archived
        ? `${user.name} archived list '${list.title}'`
        : `${user.name} sent list '${list.title}' to the board`,
    });
    await board.save();

    res.json(list);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

router.patch('/move/:id', [auth, member], async (req, res) => {
  try {
    const toIndex = req.body.toIndex ? req.body.toIndex : 0;
    const boardId = req.header('boardId');
    const board = await Board.findById(boardId);
    const listId = req.params.id;
    if (!listId) {
      return res.status(404).json({ msg: 'List not found' });
    }

    board.lists.splice(board.lists.indexOf(listId), 1);
    board.lists.splice(toIndex, 0, listId);
    await board.save();

    res.send(board.lists);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

module.exports = router;

auth.js(中间件)

const jwt = require('jsonwebtoken');
require('dotenv').config();

const auth = async (req, res, next) => {
  const token = req.header('x-auth-token');

  if (!token) {
    return res.status(401).json({ msg: 'No token, authorization denied' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ msg: 'Token is not valid' });
  }
};

module.exports = auth;

我运行整个项目时出错

错误 - 401 未经授权

回应 - 您必须是该委员会的成员才能进行更改 (我以管理员/董事会成员的身份发送请求)

member.js(中间件)

const Board = require('../models/Board');

const member = async (req, res, next) => {
  const board = await Board.findById(req.header('boardId'));
  if (!board) {
    return res.status(404).json({ msg: 'Board not found' });
  }

  const members = board.members.map((member) => member.user);
  if (members.includes(req.user.id)) {
    next();
  } else {
    res.status(401).json({ msg: 'You must be a member of this board to make changes' });
  }
};

module.exports = member;

Ps - 我在客户端 package.json 中使用代理

Github 存储库 https://github.com/JavaKaran/trello-demo

node.js reactjs express authentication mern
1个回答
0
投票

阅读您的问题并在存储库中查找您的代码后:https://github.com/JavaKaran/trello-demo

我认为发生这种情况是因为您没有将“x-auth-token”从客户端发送到服务器

您必须设置客户端请求的标头,例如:在您的 client/src/actions/board.js 中

const config = {
  headers: {
    'Content-Type': 'application/json',
    'x-auth-token': {{your_token}}
  },
};


export const addList = (formData) => async (dispatch) => {
  try {
    const body = JSON.stringify(formData);

    const res = await axios.post('/api/lists', body, config);

    dispatch({
      type: ADD_LIST,
      payload: res.data,
    });

    dispatch(getActivity());
  } catch (err) {
    dispatch({
      type: BOARD_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

希望这个答案可以帮助您解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.