Home > Blockchain >  node js jwt malformed react js
node js jwt malformed react js

Time:08-08

I'm learning backend and wrote small APIs. It all works with postman, but when I try to make this call

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]

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

and 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:

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

headers request from network I don't really understand why it doesn't work while postman calls all API successfully Thank you all

CodePudding user response:

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

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(),
];
  • Related