[SOLVED] Angular Http Post Request to a Heroku App returns 404 error

Issue

I have an Angular project that sends a POST Request to an Express Server hosted on Heroku, that should send out a mail. The issue is when I send the POST request to the server it returns a 404 error.

My goal is to send request to the server successfully.

Here is a picture if the error message.

Error log in Firefox Browser

Here is the mail.service

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
    })
  }

proxy.conf.json

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

Here is 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) {

    // Doing stuff
    res.sendStatus(200);
});

I’ve first tried with just the url, but it also could not find the url, therefore I added the proxy.conf.json. But once I’ve set it up it still could not connect to the heroku server.

On the backend side I first added cors but removed it because I thought it would block my request attempts. Does a Heroku app also have Cors on its own?

Solution

I solved the problem by adding file netlify.toml with the following code:

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


Answered By – Mike Ziegler

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *