The bearer token was not found or is currently undefined

I’ve recently encountered an issue while trying to incorporate a Bearer token into my POST route. Upon submitting a POST request using Postman, the resulting output displayed:

{
    "success": true,
    "token": "Bearer undefined"
}

Shown below is a snippet of my user.js code:

router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;

  //locate user by their email
  User.findOne({ email }).then(user => {
    //ensure user exists
    if (!user) {
      return res.status(404).json({ email: "User not found" });
    }
    //validate password
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        //successful user verification
        const payload = { id: user.id, name: user.name, avatar: user.avatar }; //generate jwt payload
        //assigning token : valid for one hour
        jwt.sign(
          payload,
          keys.SecretOrKey,
          { expiresIn: 3600 },
          (err, token) => {
            res.json({
              success: true,
              token: "Bearer " + token
            });
          }
        );
      } else {
        return res.status(400).json({ password: "Incorrect password" });
      }
    });
  });
});

// @route  GET api/users/current
// @desc   Provide details about current user
// @access Private route
router.get(
  "/current",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    res.json({ msg: "Success" });
  }
);

module.exports = router;

The root cause of this problem remains unclear to me. Any insights or recommendations would be greatly valued.

Answer №1

Could you please verify the value that is returned for keys.SecretOrKey

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

Flask fails to recognize JSON data when transmitted from Nodejs

I am encountering an issue when trying to send JSON data from Node to Flask. I am having trouble reading the data in Flask as expected. Despite attempting to print request.data in Flask, no output is being displayed. Additionally, when I tried printing req ...

Node.js Issue: Unable to connect due to ECONN Refused Error

Having recently started working with Node.js, I have encountered an error that I can't seem to resolve: Error: connect ECONNREFUSED at errnoException (net.js:901:11) at Object.afterConnect (as oncomplete) (net.js:8 ...

Exploring ways to fetch documents from a Mongoose database

I have a collection with multiple documents, each containing a long string. I need to retrieve one document at a time, as the documents only contain a long string. How can I achieve this? I used the insertMany() function to insert all documents into the c ...

Tips for generating a unique user validation hash or token

I have a registration endpoint in my express app where users need to verify their email before account activation. I'm struggling with creating a hash for the verification link. I considered using JWT, but it feels like an overcomplicated solution. Is ...

What is the reason that socket.disconnect() on the client side does not trigger the disconnect event on the server?

After implementing the following code block, my problem was successfully solved: var io = require('socket.io')(server, { pingInterval: 10000, pingTimeout: 5000, }).listen(server) I'm currently developing a chat app using socket.io. How ...

What steps can I take to stop the browser from refreshing a POST route in Express?

Currently, I am using node along with stripe integration for managing payments. My application includes a /charge route that collects various parameters from the front end and generates a receipt. I am faced with a challenge on how to redirect from a POST ...

Error: The variable <something> has not been defined

Within my GitHub project, an error stating Uncaught ReferenceError: breakpoints is not defined is appearing in the Chrome console. This issue should be resolved by including breakpoints.min.js, but it seems that webpack is somehow causing interference. I ...

Failed attempt to execute `npm install` within a docker container, resulting in the error message: "The command '/bin/sh -c npm install' exited with a code of 1."

Currently, I am facing an issue while trying to deploy my dockerized MERN stack web application to my VPS using GitLab CI/CD. The error that I encounter in my React app Dockerfile occurs when attempting to install npm packages: The service 'nowfront& ...

What are the different ways you can utilize the `Buffer` feature within Electron?

When attempting to implement gray-matter in an electron application, I encountered the error message utils.js:36 Uncaught ReferenceError: Buffer is not defined. Is there a method or workaround available to utilize Buffer within electron? ...

Why are all my axios requests being sent twice in my React-Redux application?

I have tried various solutions, but none of them seem to work for me. I am facing an issue where every Axios request is being sent twice in my React Redux Node application, which is built using Express framework in Node.js. To provide some context, let&apo ...

Mastering Authentication in React JS: Best Practices

I am currently working on integrating Backend (Express JS) and Frontend (React JS). One of the challenges I am facing is understanding how to manage sessions effectively. When a user logs in using a form built with React JS, the backend responds with a HS ...

Capture the moment a button is clicked, save it in the database, and showcase it on the page using React

This might be a challenging question, but I'm up for the challenge! I'm currently working on a website using the MERN stack, and I'd like to implement a feature where users can click a button that says "check-in", which would then store the ...

Each WSDL file seems to have a unique impact on the functionality of node-soap. An error message that I encountered states: "TypeError: Cannot read property 'postProcess' of undefined."

Currently, I am utilizing node-soap to develop a soap client. Throughout my testing, I found that most WSDL files work seamlessly with the client except for one particular WSDL file which appears to be quite complex. Interestingly, when I tested this probl ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

In Jenkins on Windows 10, an internal or external command known as Newman is not being acknowledged

I've configured newman in Jenkins to run a Postman collection. For context, I have node js installed at C:\Program Files\nodejs and globally installed newman at C:\Users\waniijag\AppData\Roaming\npm\node_module ...

Executing NodeJS custom middleware to show parent function being called

Goal: Showcase the parent function of a middleware function shared = require('./RoutFuctions'); app.post('/link', shared.verifyToken, (req, res) => { ... } In the middleware function exports.verifyToken = functio ...

Installation using npm stalls in a Docker container

I encountered an issue while trying to launch my react docker container (https://github.com/AndrewRPorter/flask-react-nginx). The installation process stalls after displaying multiple warnings. The OS I am using is Ubuntu. It seems like there might be som ...

Quick shortcut for efficiently stopping a node process and releasing the occupied port

Hello everyone, I have a question that has been discussed before with different perspectives. I am wondering if any of you are aware of the secret hotkey in Ubuntu to terminate a node process without running into the EADDRINUSE ::XXXX problem upon restarti ...

Executing two asynchronous functions

As someone who is new to async and await, I am contemplating the possibility of calling two Stripe APIs within an express api endpoint. Can this be done? server.post('/ephemeral_keys', async (req, res) => { let customerId = req.body[" ...

Minimize the amount of storage required for storing user IDs in Node.js, Express.js, and Feathers.js

I am currently working on my first project using Node.js and Feathersjs for the backend, with Vue for the frontend. In the database, the user IDs are stored as character strings like "IXS1rCoGogkdOOss". It seems like storing user IDs as integers would be ...