node js jwt malformed react js


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 {
      const fields = {title,tags,text,imageUrl,};
      const { data } = await"/posts", fields);
      const id = data._id;
    } catch (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;
  } catch (error) {
      message: "Can't resolve",

Function call on backend:"/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;
    } catch (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


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 😀

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(),

Answered By – Daniil Galitskii

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published