Error 404 returned when making an Angular HTTP POST request to a Heroku application

I am currently encountering an issue with my Angular project, where I am trying to send a POST Request to an Express Server hosted on Heroku in order to send out an email. However, every time I send the POST request to the server, I receive a 404 error.

My ultimate goal is to successfully send the request to the server without any errors.

Attached below is an image displaying the error message:

https://i.sstatic.net/saaMK.png

Below is the mail.service code snippet:

sendEmail(name: string, email: string, termin: string, text: string): Observable<any> {
    return this.http.post<any>(`/api/email`, {
      name: name,
      email: email,
      date: termin,
      text: text
    })
  }

Now moving onto the proxy.conf.json file:

{
  "/api/email": {
    "target": "{url to heroku app}/api/email",
    "secure": true,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

Next, here is the configuration for the expressjs server:

// Imports cors, body parser, express
var app = express();


var allowList = ['localhost:4200', 'http://nmma.netlify.app', 'http://nmma.ch']

app.use(bodyParser.json());
/*
app.use(cors({
    origin: function (origin, callback) {
        console.log(origin);
        if (allowList.indexOf(origin) === -1) {
            var msg = 'The CORS policy for this site does not allow access from the specified Origin.'
            return callback(msg, false);
        }
        return callback(null, true);
    }
}));
*/

var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
});

app.post("/api/email", function (req, res) {

    // Handling email sending logic
    res.sendStatus(200);
});

I initially attempted to use just the URL, but it resulted in not being able to locate the URL. Thus, I implemented the proxy.conf.json. Despite setting it up, the connection to the heroku server still could not be established.

Additionally, on the backend side, I included cors which was later removed as I suspected it might have been blocking my request attempts. A question that arises is whether a Heroku app also comes with its own Cors implementation?

Answer №1

To resolve the issue, I implemented a solution by creating a file named netlify.toml and including the code snippet below:

[[redirects]]
  from = "/api/email"
  to = "https://nmma-backend.herokuapp.com/api/email"
  status = 200
  force = true


Answer №2

Have you initialized your server using the proxy configuration? Ensure to start it with

ng serve --proxy-config proxy.conf.json
. If that's the case, consider setting secure to false and restart the server.

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

Information is not stored in the mongoDB database using node.js

Currently, I am working with node.js code and attempting to insert data into a mongodb database using Postman (POST) but unfortunately, the data is not being saved properly. Only _id and __v fields are getting inserted into the documents automatically. I s ...

Encountering an issue with the message: "Property 'ref' is not available on the type 'IntrinsicAttributes'."

Having trouble implementing a link in React and TypeScript that scrolls to the correct component after clicking? I'm using the useRef Hook, but encountering an error: Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assi ...

Tips for developing projects that are compatible with various versions of Angular, including Angular 2, 4, 5,

I have a Windows 8 system with Angular CLI version 6.1.1 installed. I am trying to create projects for Angular versions 2, 4, 5, and 6. However, when I use the command below to create a new project: ng new demo The package.json file contains the follow ...

The Angular application shell build has produced two new folders within the dist directory. I'm curious about their purpose and how they can

Whenever I execute the ng run my-app:app-shell -c production command, it creates 2 folders within the dist directory - one for the browser and one for the server. Now, I find myself with 2 different commands to use: npm build --prod (for a regular build) ...

Combining an array into another array using the same key in JavaScript

My goal is to merge the array itself and transform it into a more meaningful array array = [ {item: 'pen', madeIn: 'US', color: 'blue'}, {item: 'pen', madeIn: 'US', color: 'white'}, {item: ' ...

What could be the reason behind encountering a "Cannot return null for non-nullable field" error while attempting a mutation?

Exploring (Apollo) GraphQL on the server side has presented me with a puzzling issue. I have been attempting to register a user, but I keep encountering the error documented in the linked image below. What could be causing this problem? Let's disregar ...

Exploring the Validation of Forms in Angular for Practical Implementations

I'm curious to know whether creating a simple form validation process can really be as complicated as it seems, or if I may be overlooking something. It's fairly straightforward to demonstrate the power of form validation in a tutorial setting. ...

Replace Material UI propTypes with new definitions

I am currently working with React, Typescript, and Material UI. To globally disable the ripple effect for the ListItem component, I am using createMuiTheme.props in the following manner: createMuiTheme({ props: { MuiListItem: { disableRipple: t ...

Navigating back to the previous page with data in Angular 4 after switching from Angular 2

One scenario to consider is when page C features a Go Back button. On Page A, navigate to Page C with data and click the Go Back button to return to Page A with data. Similarly, on Page B, go to Page C with data and press the Go Back button to go back to ...

What role do the esm directories serve within Angular 2 modules?

Currently, I am working with Angular2 RC4 and using the following packages: "@angular/common": "2.0.0-rc.4", "@angular/compiler": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", "@angular/forms": "0.2.0", "@angular/http": "2.0.0-rc.4", ...

Update and send back variable on the spot

I'm interested in learning the syntax for creating an inline function that can accept a parameter, perform a simple modification on it, and return it all in a single line. Here's an example: (input) => { input.status = 'complete'; ...

Error encountered: No geographic indices found for executing a geoNear operation with Mongoose

Initially, I had divided the schemas but later nested them inside my overall document. Despite adding indexes and removing coordinates from location, there seems to be an issue with the nested points. Upon running get Indexes, it shows that there is an i ...

How can we use Node.js and Express to create routes with functions that accept multiple parameters?

When it comes to Express routes, I often come across different formats and have some questions about passing multiple parameters to app.get(). I am familiar with the standard usage involving a callback function like function(req, res), but I am confused a ...

TypeScript encountered an error (TS2403) stating that subsequent variable declarations must have matching types

Encountered an issue with my typings.d.ts file Error TS2403: Subsequent variable declarations must have the same type. Variable 'module' is expected to be of type 'NodeModule', but is currently of type '{id:string}'. declare ...

In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it. const AdminRoutes: FunctionComponent = () => { const ...

Angular 14: Deleting an item from a FormArray triggers unintended form submission due to Angular animation

After beginning to create animations for my app, I observed that deleting an element from a FormArray triggers a form submission. Custom form controls were developed using ControlValueAccessor, and certain FormGroups are passed through @Inputs. The animati ...

Having difficulty retrieving data from inner join table using axios in React

As a newcomer to React, I'm attempting to populate fields with data retrieved from Express using Axios. However, I am encountering difficulties when trying to display data from a joined table. import React, { Component } from "react"; import FilmesDa ...

ERROR: Unable to call function getTime in Typescript

While working on my function in Typescript, I encountered an issue with two sets of data in the database - date and time, both expecting strings. When users select a date, I trigger a POST request to set the time for them. To handle this scenario, I creat ...

Sharing Node/Express Sessions Between Client and Server

After searching for answers, it seems that my issue is unique and I may have been using the wrong search queries. The project I am working on involves a react app with server-side rendering. There is also another server responsible for handling the entire ...

What is a simple method to convert TypeScript to JavaScript?

Is it possible to eliminate TypeScript-specific keywords from a JavaScript file without using the tsc command, while ensuring that the file remains readable by humans and maintains JSX syntax? ...