I'm having trouble adding headers to my axios post request. The post route functions correctly in Postman but does not work when using axios. Can anyone

Implementing JWT for protecting a post route in my nodejs, express, react application has been quite a challenge. While testing with postman and adding the JWT token to the headers works flawlessly to add users to the database, I encounter a 401 response (Unauthorized) when making the request from react using axios.

Below is the axios post request from the front end:

addClient = async e => {

let newUser = {
                businessname: businessname.toLowerCase(),
                firstName: firstName.toLowerCase(),
                lastName: lastName.toLowerCase(),
                email,
                username,
                password,
                phoneNumber,
                customerStatus: customerStatus.value,
                userType,
                Gooduntil
            };
            const accessString = localStorage.getItem("JWT");
            await Axios.post("/auth/signup", newUser, {
                headers: { Authorization: `JWT ${accessString}` }
            })
                .then(res => {
                    console.log(res);
                    return this.setState({
                        loadingAxiosReq: false
                    });
                })
                .catch(err => {
                    return console.log(err);
                });
}

The post route looks like this:

router.post("/signup", verifyToken, (req, res) => {
    console.log(req.headers);

    const {
        businessname,
        username,
        firstName,
        lastName,
        phoneNumber,
        email,
        password,
        customerStatus,
        userType,
        Gooduntil
    } = req.body;

    if (password.length < 8) {
        throw "Password must be at least 8 characters";
    } else {
        User.findOne({
            where: {
                email
            }
        }).then(user => {
            if (user) {
                return res.send("Email already exists!");
            } else {
                const encryptedPassword = bcrypt.hashSync(password, salt);

                let newUser = {
                    businessname,
                    username,
                    firstName,
                    lastName,
                    phoneNumber,
                    email,
                    password: encryptedPassword,
                    customerStatus,
                    userType,
                    Gooduntil
                };
                User.create(newUser)
                    .then(() => {
                        // newUser.isAdmin = true
                        delete newUser.password;
                        res.send(newUser);
                    })
                    .catch(function(err) {
                        console.log(err);
                        res.json(err);
                    });
            }
        });
    }
});

And here's the middleware being used:

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {
    const token = req.header("JWT");
    if (!token) return res.status(401).send("Access Denied!");

    try {
        const verified = jwt.verify(token, process.env.JWT_SECRET);
        req.user = verified;
        return next();
    } catch (err) {
        res.status(400).send("Invalid Token!");
    }
};

If you have any suggestions on how to successfully make the axios request, it would be greatly appreciated. Thank you!

Answer №1

It appears that you are checking for a header named JWT based on this line.

const token = req.header("JWT");

However, in axios, you are actually sending the Authorization header:

{ headers: { Authorization: `JWT ${accessString}` }

To resolve this issue, make sure to send the JWT header. Alternatively, if you wish to check the Authorization header, simply look for that specific header:

const token = req.headers['authorization'];

Additionally, only send the <token>. If you are sending JWT <token>, then you will need to separate the header and verify only the <token> part.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...

Unable to retrieve the initial return value from the function that has been promisified

Previously, the code functioned correctly but was not properly promisified. const express = require('express'); function runServerAndReturn() { app = express(); console.log('Before starting server'); const server = app.lis ...

Ways to retrieve or access data from another collection in Mongoose

I am looking to retrieve the collection of restaurantOffer data when querying restaurant data. My database Model is as follows Restaurant.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const restaurantSchema = new Sc ...

Utilize Jquery to send a POST request and obtain a corresponding reply from the Node

I'm encountering a minor challenge. I want to make a simple HTTP POST request using AJAX jQuery to a Node.js server and have the server respond accordingly. Unfortunately, I haven't been successful in retrieving the response from the server. I wo ...

Is there a way to increase the size of a Card by hovering over it in Material UI?

I am currently working with Material UI and would like to implement a feature where a Card component enlarges upon hovering, similar to the example shown here What is the best way to achieve this effect? I have tried using the raised property but it doesn ...

Error encountered in lodash.js in Angular 2 framework

I have been attempting to implement lodash for a datatable. Here are the steps I followed: First, I tried running npm install lodash, but encountered an error stating that the package could not be found After researching the issue, I attempted npm in ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

What is the integration process of using Font Awesome with React?

After installing react-create-app using npm, I also added react-fontawesome. Now, I'm wondering how to include the css styles of fontawesome in my project? Here is a glimpse of my work space: https://i.stack.imgur.com/pM1g1.png ...

performing unauthorized action on an opened directory

I'm having trouble uploading a file using express-fileupload. The file is not moving to the directory I specified. I tried the same code in another project and it worked fine, but for some reason, it's not working in my current project. ...

Implement error handling middleware when utilizing express.Router

I am looking to implement express.Router in my application. I currently have an index file that serves as the server, and a routes file that defines some express routes using express.Router. My goal is to ensure that whenever one of my routes fails, it tr ...

By utilizing the HTML element ID to retrieve the input value, it is possible that the object in Typescript may be null

When coding a login feature with next.js, I encountered an issue: import type { NextPage } from 'next' import Head from 'next/head' import styles from '../styles/Home.module.css' import Router from 'nex ...

Acquiring backend information to display in front-end using ReactJS

I receive data from the backend to present it in the following font: componentDidMount() { const response = this.props.store.privateImputationData; console.log(response); } When I check the console, it shows null. However, if I use a setTimeout, it w ...

Leveraging OnMounted and Axios Requests in Pinia

I am currently developing a website that showcases a range of products with dedicated product pages. However, I am facing challenges in determining the optimal sequence for loading data. While I could make an axios call and pass the data as a prop to subse ...

Encountered an error involving the SequenceExpression node type while using Jest

While adding a snapshot test to my React code, I encountered an unexpected error message: Unexpected node type: SequenceExpression (This is an error on an internal node. Probably an internal error. Location has been estimated.) The code transpiles withou ...

What is the correct way to utilize theme overrides for changing the color of the MUISwitch "bar" when it is in the checked state?

Upon reviewing the source code on Github, I attempted the following solution. While it worked, a warning appeared in the console. const customTheme = createMuiTheme({ overrides: { MuiSwitch: { checked: { "& + $bar": { opa ...

React - Incorrect use of hooks and class components

Understanding hooks as the opposite of a class component can be confusing. A simple line of code can trigger an error when trying to adapt it for use in a class component. Take, for example, this situation: .jsx files and functional components work seamles ...

What is the reason that using "/*" invalidation alone is not enough to effectively clear the React build in an s3 bucket from cloudfront?

When I upload my React application to an S3 bucket, I need to invalidate the old build in CloudFront. So far, I have tried a few invalidation patterns without much success. It seems that I have to specifically invalidate the /static/js/main.xyz.js file f ...

A method for assigning a single event listener to multiple events in a React component

I find myself in a situation where I have two events, onClick and onSelect, both of which share the same event handler. I am wondering what the most efficient way to handle this scenario would be - should I create a common method and then call the event ...

What steps can I take to get Node.js up and running smoothly once more?

Lately, I have been using npm to work on a project with angular. However, 3 days ago, after my Windows system updated, npm stopped working completely. When I tried to run npm install The terminal displayed the following error: npm ERR cb() never called! ...

Customizing Material-UI styles with type overrides

Is there a way to change the MuiIconButton-root class when using MuiSvgIcon with the fontSizeSmall attribute? import React from 'react' import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles'; const theme = createMuiT ...