Home > Software engineering >  how to set headers in axios patch request in react js
how to set headers in axios patch request in react js

Time:01-22

Can someone tell me what mistake I am making or tell me how to set the header in axios patch request. when I am running the API through postman, everything is working fine but when I connect it with the front end, an error comes up saying that the JWT is not provided on the backend

here is the frond end code :

import React, { useEffect } from 'react';
import { useParams } from 'react-router';
import axios from 'axios';

const Loader = () => {
  const parmas = useParams();
  const { id } = parmas;
  console.log(id);

  useEffect(() => {
    const fetchBags = async () => {
      try {
        const res = await axios.patch('http://localhost:4001/public/verify', {
          headers: {
            'Content-Type': 'application/json',
            Token: id,
          },
        });

        console.log(res);
        console.log('CBM', { res });
      } catch (error) {
        console.log(error);
      }
    };
    fetchBags();
  }, []);
  return <div>this is loader</div>;
};

export default Loader;

below is my backend code:

export const verifyUser = async (data) => {
  const token1 = data.header("Token");

  try {
    const verified = jwt.verify(token1, getTokenSecret());
    console.log(verified)
    await userModel.verifyUser(verified);
    return {
      message: "success",
    };
  } catch (error) {
    console.log(`Auth Service > verifyUser > ${error.toString()}`);
    throw error;
  }
};

this error is comming: Error

CodePudding user response:

From docs

axios.patch(url[, data[, config]])

As you can see you pass config in 3rd argument not 2nd.

const res = await axios.patch(
  'http://localhost:4001/public/verify',
  {}, // data (2nd argument)
  {
    headers: {
      'Content-Type': 'application/json',
      Token: id,
    },
  } // config (3rd argument)
)

  • Related