"Upon submitting a post request on my Heroku express app, an unexpected application error

Just deployed my app on heroku for the first time. Everything runs smoothly with GET requests, but encountering an application error when attempting to make a POST request with a body.

After checking the logs on heroku, it appears that there is an issue with MongoDB authentication. Oddly enough, the code works fine when run locally. It's worth noting that I have allowed access from any IP using 0.0.0.0/0

Implemented a solution found online by setting up the headers in app.use like this:

app.use((req, res) => {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
})

This is the POST request in the Express app:

app.post('/newOrder', async (req, res) => {
    res.header('Access-Control-Allow-Origin: *')
    const { fullname, phone, textMsg, currentItems, total } = req.body
    let message = []
    let inputType = []

    // Checking for validation of input fields

    if (fullname.length === 0) {
        const errMsg = 'This field cannot be empty'
        message.push(errMsg)
        inputType.push(0)
    }

    if (phone.length === 0) {
        const errMsg = 'This field cannot be empty'
        message.push(errMsg)
        inputType.push(1)
    }

    if (!(/^[a-zA-Z\u0590-\u05FF\s]+$/.test(fullname))) {
        const errMsg = 'Full name must contain only letters and spaces'
        message.push(errMsg)
        inputType.push(0)
    }
    
    // more validations...

    if (inputType.length !== 0) {
        return res.status(400).json({
            message,
            inputType
        })
    }

    // Creating new ticket and saving to database

    const newTicket = new Ticket({
        fullname,
        phone,
        textMsg,
        items: currentItems.map((data) => data.desc),
        total
    })
    
    await newTicket.save()
        .then(async (order) => {
            // Sending mail after saving order
            const isMailSent = await mailTicket(fullname, phone, textMsg, currentItems, total, order)
            if (!isMailSent) {
                return res.status(400).json({
                    mailError: true,
                    message: 'Temporary error in sending the order to the designer - contact designer directly'
                })
            }
            return res.status(200).json({
                orderId: order._id
            })
        })
})

Any ideas on what might be causing this issue?

Answer №1

Success at last:

  1. The .env file was being overlooked
  2. This caused issues with the database connection

To resolve the issue, changes were pushed to Heroku without including .env variables. Credentials were explicitly stated in app.js.

Learn how to set .env variables on Heroku

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

Encountering an issue when starting a Node.js/Swagger application using pm2 within a Docker environment: Unable to

1. Overview: I successfully developed a basic application using Node.js, Express, and Swagger by following this informative tutorial, along with the help of generator-express-no-stress. However, when I attempt to run the application within a Docker contai ...

Passing information from the frontend to the backend in a ReactJS/NodeJS application: A guide on sending

Currently, I am in the process of developing a website and looking to enhance my API functionality. My setup includes a frontend React app and a backend Express Node.js server. In addition, I have a local webserver that contains information on football ma ...

delivering properties through React server side rendering

I'm having difficulty passing initial props to my React component from my Node (express) server-side rendering. Here's a summarized version of the component: /* mycomponent.jsx */ import React, {PropTypes, Component} from 'react/addons&apo ...

Tips for optimizing nested object array searches

Is there a widely recognized technique to chain .map or .filter or .find functions in order to achieve this type of search? Imagine an array of objects nested within another array of objects customerGroups : [ { id: 1, customers: [{ id ...

What is the best way to establish a page-specific API endpoint in Next.js?

How can I specify the API pathname for different pages in my project? This is the folder structure I am working with: src ├── component │ ├── common │ └── layout ...

Fade images using jQuery when hovered over

Is there a way to create an interactive image that cycles through multiple images when hovered over, and returns to the original image when the mouse moves away? I'm aiming for a smooth fade effect between images, like transitioning between 3 or 4 dif ...

Retrieve the computed value of a cell in an Excel spreadsheet using Node.js

Utilizing node.js in tandem with the exceljs module to process my Excel sheets. Writing values into specific cells while others already contain formulas. Seeking a method to trigger those formulas and programmatically store the resultant values in the she ...

Getting a random value within a Struts set tag can be achieved by utilizing the <

Using struts2 tags in my application, I am trying to dynamically change the value in a JavaScript array using s:set tags. However, when I add the values dynamically, the output I get is 2012 - diff + 1, whereas I am expecting 2011. How can I achieve this? ...

React application created with create-react-app that uses multiple environment files for varying configurations

I've been working on setting up various environment files for a React project (using create-react-app). I referred to the official documentation, but I encountered the following error: '.env.development' is not recognized as an internal or ...

Determine whether the user has authorized the website with long-term access to obtain location information in the browser

Everything is running smoothly as I call navigator.geolocation.getCurrentPosition in my web app. Users are guided to a screen that explains the benefits of sharing their location, and once they press a button, the request is initiated without any issues. ...

Unable to conceal iFrame ribbon in Sharepoint Online

Attempting to conceal an Office 365 ribbon in SharePoint, but encountering an issue... TypeError: document.getElementById(...) is null This is the snippet I'm experimenting with; I plan to implement display:none later... document.getElementById(&ap ...

Applying custom styles to the initial 5 elements post clicking the button with Jquery

I have a set of HTML codes containing multiple buttons. <div class="main"> <div class="button hide">1</div> <div class="button hide">2</div> <div class="button hide">3</div> <div class="button h ...

I find myself facing a roadblock in navigating Servlets and HTML

I'm currently immersed in a project aimed at launching an innovative online food ordering platform. To bring this vision to life, I've harnessed the power of HTML, CSS, and JavaScript for frontend development, Java (Servlets) for backend function ...

Typescript enhances the functionality of the Express Request body

I need help with the following code snippet: const fff = async (req: express.Request, res: express.Response): Promise<void> => {...} How can I specify that req.body.xxx exists? I want it to be recognized when I reference req.body.xxx as a propert ...

There seems to be an issue preventing the Chrome browser from launching with the error message: "ERROR: connect ECONNREFUSED 127.0

My setup includes: Operating System: Windows 10 (64 bit) Browser: Chrome version 58 Node.js: 6.10.1 Npm: 3.10.10 Chromedriver: 2.29.0 After running my tests with Chrome using Selenium standalone, I encountered an error in the console where Selenium was ...

When the button is clicked, send data using 'POST' method to the php file and fetch

<script> $(document).ready(function(){ $("#vE_rebtn").click(function{ var reverifyEmail = '<?php echo $_SESSION["verifyEmIPv"]; ?>'; $('#rE_rebtn').hide(); $('#re_ ...

Steps for retrieving error code from a JSON error message

The error message is displayed as follows: "{\"errorCode\":\"2029\",\"errorMessage\":\"Duplicate Entry\"}" How can I retrieve the errorCode from the above code using ...

Using three.js to create a hover effect that highlights the edges of a cube with LineSegmentsGeometry

I am currently utilizing LineSegmentsGeometry and LineMaterial to render thick cube edges. My objective is to dynamically change the color of the edge when it is hovered over. const edgesGeometry = new LineSegmentsGeometry().fromEdgesGeometry( new THREE. ...

Steps for updating object state in React

Here is the code snippet that I am working with: this.state = { user: null } I am trying to figure out how to set the name property of the user when it exists. Unfortunately, using this syntax this.setState({user.name: 'Bob') doesn't ...

How can we use the useState hook in React to dynamically generate state variables?

I'm currently working on a React app where input fields need to be stored in the state. While I can use the useState hook to easily store these values, the challenge I'm facing is that I don't know what fields are needed since they are retri ...