简体   繁体   English

节点js jwt 畸形反应js

[英]node js jwt malformed react js

I'm learning backend and wrote small APIs.我正在学习后端并编写小型 API。 It all works with postman, but when I try to make this call这一切都适用于 postman,但是当我尝试拨打这个电话时

const onSubmit = async () => {
    try {
      setIsLoading(true);
      const fields = {title,tags,text,imageUrl,};
      const { data } = await axios.post("/posts", fields);
      const id = data._id;
      navigate(`/posts/${id}`);
    } catch (error) {
      console.warn(error);
      alert("Error while creating post");
    }
  };

I have this error我有这个错误

JsonWebTokenError: jwt malformed at Object.module.exports [as verify] JsonWebTokenError: jwt 在 Object.module.exports 格式错误 [作为验证]

Request controller:请求 controller:

export const create = async (req, res) => {
  try {
    const doc = new PostModel({title: req.body.title, text: req.body.text, 
tags: req.body.tags, imageUrl: req.body.imageUrl, user: req.userId, viewsCount: req.body.viewsCount, });
    const post = await doc.save();
    res.json(post);
  } catch (error) {
    console.log(error);
    res.status(500).json({
      message: "Can't resolve",
    });
  }
};

Function call on backend: app.post("/posts",checkAuth,postCreateValidation,handleValidationErrors,create); Function 调用后端: app.post("/posts",checkAuth,postCreateValidation,handleValidationErrors,create);

and axios:和 axios:

import axios from "axios";
const instance = axios.create({
  baseURL: "http://localhost:4444",
});
instance.interceptors.request.use((config) => {
  config.headers.Authorization = window.localStorage.getItem("token");
  return config;
});
export default instance;

checkAuth middleware: checkAuth 中间件:

import jwt from "jsonwebtoken";
export default (req, res, next) => {
  const token = (req.headers.authorization || "").replace(/Bearer\s?/, "");
  if (token) {
    try {
      const decoded = jwt.verify(token, "secret123");
      req.userId = decoded._id;
      next();
    } catch (error) {
      console.log(error);
      return res.status(403).json({ message: "forbidden request" });
    }
  } else {
    return res.status(403).json({ message: "forbidden request" });
  }
};

来自网络的标头请求 I don't really understand why it doesn't work while postman calls all API successfully Thank you all我真的不明白为什么它不起作用,而 postman 成功调用所有 API 谢谢大家

So, one day let me understand that I've made wrong tags format checking for the Post creation.所以,有一天让我明白我为帖子创建做了错误的标签格式检查。 I've made it properly and all started work:D我已经做好了,一切都开始了:D

import { body } from "express-validator";

export const postCreateValidation = [
  body("title", "Insert post title").isLength({ min: 3 }).isString(),
  body("text", "Type post text").isLength({ min: 10 }).isString(),
  body("tags", "Wrong tags type").optional().isString(), //changed isArray on isString
  body("imageUrl", "Wrong URL type").optional().isString(),
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM