Axios and Express are throwing an error of "response is not defined

I'm facing an issue with the post method in my back-end code. Here's a simplified version of it:

router.post('/users', async function(request, response) {
  try {
    const userToRegister = request.body;
    const user = await CreateUserService.execute(userToRegister);
  
    return response.json(user);
  } catch (err) {
    console.log(err);
    return response.status(401).json({ message: 'email already registered' });
  }
});

When I try to handle the response on the front end to check for duplicate users, like this:

api.post('users', user.userFields)
      .then(response => {
        console.log(response)
      })
      .catch(err => {
        console.log(err);
      })

The response is always undefined.

If I add return response.json(err); in the backend code, it works fine.

What am I missing here?

Answer №1

Disregard the previous messages, I have located the mistake.

The issue was within the user exception block of CreateUserService.

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

Is it possible to exclusively render meta tags as SSR on my website?

My website is fully developed using React for the frontend and NodeJs + Express for the backend. I am looking to implement dynamic OG (Opengraph) Tags for a specific route that is used by a specific component. Converting this component to SSR may be chall ...

The program encountered an issue with the binding app/nodes_modules/node-sass and could

When running the command: $ yarn run production An error occurs (for every .scss file in the project) : ERROR in ./resources/assets/sass/guest.scss Module build failed: ModuleBuildError: Module build failed: Error: Missing binding /app/node_module ...

Encountering EPIPE error in Webpack Build on Linux Subsystem Only

When running Webpack from the command line using the Windows version of installed node/yarn, my project compiles perfectly fine. However, if I attempt to do a Webpack build from the Linux subsystem, it breaks with the following error: events.js:167 ...

Issue: Attempting to set headers after they have already been sent when iterating through an array of objects and executing asynchronous database calls

A specific controller function handles incoming post requests, where the request body contains an array of objects structured as follows: [ { "names": ["test company 1","test company 2"], "role": ...

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...

Saving user input from a React JS form to a MySQL database

Seeking assistance on how to insert name field data into a MySQL database using Express.js and the Fetch API. Any guidance on flow and project structure would be much appreciated. Thank you in advance. class NameForm extends React.Component { constru ...

Building a Friendship Connection System using Express and MongoDB

I have the task of implementing a feature that allows users to send friend requests similar to Facebook and other social media platforms. While I have started creating this functionality, my progress has been hindered by my lack of experience with mongoDB ...

Error: Attempting to create a Discord bot results in a TypeError because the property 'id' is undefined

While working on a basic Discord bot, I encountered an issue when running the -setcaps command. The error message I received was: TypeError: Cannot read property 'id' of undefined. I'm unsure about what might be causing this error. Any a ...

Node.js application - varying NODE_ENV upon NPM launch

Operating my node.js application can be quite confusing. When launched by npm start, it operates in "production" mode, whereas when launched using node start.js, it runs in 'development' mode. I want to ensure that the 'development' mo ...

Restricting the Amount of Messages Processed by a Receiver in NodeJS with RabbitMQ

I'm currently working with the amqplib node module and following a tutorial on sending and receiving messages in RabbitMQ. Check out the tutorial here My receivers/workers are responsible for handling CPU intensive tasks, so I've limited them t ...

Error: An unexpected issue occurred when attempting to iterate over the snapshot

I recently started exploring nodejs and Google Cloud FireStore. Below is the code that I am currently working on. createNewPage = function (title, header, content, db ) { let pageRef = db.collection("pages").doc(title.trim()); let setPage = pag ...

Does my API call continue to create a record after the return statement has been executed?

I encountered a peculiar issue with my code. Even though the database validation confirms that a record already exists, and I receive a 500 status from the API call, it still manages to create a duplicate entry in my table. exports.createBet = async (req, ...

What is the best way to send multiple responses from an Express server using res.write and execute a specific action after each write operation?

I currently have an active express server that is sending data using res.write() Fetcher.js function fetcher() { console.log("fetcher function called") fetch('/units.html', { method: "POST", body: JSO ...

Encountered an error while web crawling in JavaScript: Error - Connection timeout

I encountered an error while following a tutorial on web crawling using JavaScript. When I execute the script, I receive the following errors: Visiting page https://arstechnica.com/ testcrawl ...

What could be causing the issue with creating new comments in my node.js application?

I am encountering an issue while attempting to add a new comment in my node.js application. Specifically, I am trying to create a comment under specific posts using the post's path. Below are the relevant parts of my code: Comment Model const mongo ...

Employing Nginx as a reverse proxy for node.js while disregarding the use of websockets

Currently, I have nginx 1.5 set up as a proxy to my nodejs express app for serving static content and enabling websocket transport by upgrading the http version to 1.1. To further enhance performance, I am looking to implement reverse proxy caching. Howev ...

Having trouble performing an Image (base64) update in Next.js

Hi everyone, I'm facing a challenge with updating the image data in my code. The base64 string data updates correctly and the new image is displayed before submitting the data. However, once I submit the data, the image doesn't update. Below is ...

Mongoose fails to produce an error message when the database command is unable to execute

Exploring the realm of Mongoose error handling, specifically when issues arise due to a dropped connection to the database during or just before the execution of a db command. Consider the following code snippet: var myModel = new MyModel(data); myModel.s ...

What is the best way to utilize a portion of the data retrieved from an API call as the output for a function?

After extensive research and testing, I have been exploring ways to make API calls in node js. Currently, my focus is on utilizing a portion of the JSON object returned from an API call within a module to generate a Token. var request = require("request") ...

Attempting to retrieve a local plugin from a remote registry in Visual Studio 2015 Release Candidate

I am facing an issue with installing a local plugin to my Cordova project. Even though I add it through Visual Studio without any problems, the build process using plugman fails because it attempts to retrieve the plugin from the npm registry at "http://re ...