Axios POST Request works on localhost but no longer works after deploying on Netlify

Hi there! I have an error while axios post request after deploying on Netlify. The error is:

Failed to load resource: the server responded with a status of 404 ()
createError.js:17 Uncaught (in promise) Error: Request failed with status code 404
at e.exports (createError.js:17)
at e.exports (settle.js:19)
at XMLHttpRequest.d.onreadystatechange (xhr.js:60)

Request:

axios({
        method: 'POST',
        url:'/send',
        data: {
          name: name,
          email: email,
          messsage: message
        }
})
.then( ( res ) => {
        if ( res.data.msg === 'success' ) {
          this.resetForm();
          this.setState( {display: 'none'} );
          this.setState( { showModalSuccess: true } );
        } else if ( res.data.msg === 'fail' ) {
          this.setState( {display: 'none'} );
          this.setState( { showModalError: true } );
        }
})

Server:

const express = require ('express');
const nodemailer = require('nodemailer');
const bodyParser = require("body-parser");
const path = require('path');
const cors = require('cors')
const config = require('./config.js');
const app = express();

app.use(cors());

app.use(
  bodyParser.urlencoded({
    extended: false
  })
);

app.use( bodyParser.json() );

app.post('/send', (req, res) => {
const output = `
   <p>You have a new contact request</p>
   <h3>Contact Details</h3>
   <ul>
     <li>Name: ${req.body.name}</li>
     <li>Email: ${req.body.email}</li>
   </ul>
   <h3>Message</h3>
   <p>${req.body.message}</p>
 `;

// Create reusable transporter object using the default SMTP transport
   let transporter = nodemailer.createTransport({
    host: 'smtp.ethereal.email',
    port: 587,
    secure: false, // true for 465, false for other ports
    service: "ethereal",
    tls:{
      rejectUnauthorized:false
    },
    auth: {
      user: 'email.email',
      pass: 'pass.pass'
    }
  });
  transporter.verify((error, success) => {
    error ? console.log( error ) : console.log( 'Server is ready to take message' )
  });

// setup email data with unicode symbols
  let mailOptions = {
   from: `${req.body.email}`,
   to: 'jorge.crooks@ethereal.email',
   subject: 'A new request frow web page', // Subject line
   // text: '', // Plain text body
   html: output // HTML body
  };

// Send mail with defined transport object
  transporter.sendMail(mailOptions, (error, data) => {
    if (error) {
      res.json({
        msg: 'fail'
      })
      console.log(error);
    } else {
      res.json({
        msg: 'success'
      })
      console.log('Message sent: %s', data.messageId);
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(data));
    }
  });
});

app.listen( config.server.port, () => {
  console.log( `Server running on port ${ config.server.port }` );
} );

Can smbd help?

Hi, @xlakostax. Where is the server running?

It is a Netlify Function or is it deployed to another service (such as Heroku or AWS Lambda)?

Hi @Luke! What do u mean “Netlify Function”? I apologize, I am not experienced in Netlify so far. I just create a relationship between my Netlify acc and my Git. The server is a part of a project. And I have to mention I use React Router for navigation. It seems the problem is due to it.

Ah, ok, thank you for that explanation. Servers won’t run on Netlify, please check out this post to learn more: [Common Issue] Can I run a web server, HTTP listener, and/or database at Netlify?

Hope that helps!

Hey there,
So I am having I feel a similar issue, I have a simple react chat app hosted on netlify and the back end hosted on heroku, my app works like a charm locally, but since deploying to netlify I get a CORS error telling me access has been blocked etc, I have my environment variables setup in my env, I even tried adding a redirect, on my express server CORS is also setup. Can you or anyone else help me with this? Is there something I am doing wrong, all the countless posts and links I have read have not helped me to resolved this.

hi frankie, sorry that you are having trouble getting this to work. Do you have a netlify site URL you can share?

Hey Perry,

Thank you for responding so fast. Here is the url to my netlify site.

https://mentally-me-chat-v1.netlify.app/

the backend is hosted on Heroku. I get the cors error when i try to do a login or sign up.

Hey @Frankie_Bukenya Frankie, I believe you’ll have to set CORS headers on your server side. Here’s a StackOverflow post that may be helpful:

That person is using fetch as opposed to axios, but it looks like you’ve already included the axios way—withCredentials: true attribute—to your code :slight_smile:

Let us know if adding those headers on the backend works for you and if we can answer any other questions on this.

Hi guys!! I’m having similar issue, it worked fine locally but now I’m getting an error. frontend - netlify, backend - heroku!

POST https://erickperez.info/api/contact-me 404 Uncaught (in promise) Error: Request failed with status code 404 at e.exports (createError.js:16) at e.exports (settle.js:17) at XMLHttpRequest.p.onreadystatechange (xhr.js:61)
I tried the previous solutions but it is not working, it has been too many days, please help!!

this is the link of my page: https://erickperez.info/contact-me

Thank you guys!!!

Hi Veronica and welcome to our community! We don’t accept POST requests, so I am not sure what you’d expect besides a 404 to that route (which I think we do host)? If you are trying to send a form submission, you’ll need to either:

  • use our form handling feature; we DO accept posts to the path you configure for action= in your HTML form definition (I understand you are using javascript to post; our feature requires a plain html version of the form though): https://docs.netlify.com/forms/setup/
  • post to a function (https://docs.netlify.com/functions/overview/) - those can accept POSTs
  • post to another service that is expecting your data.

Perhaps you meant to set up a proxy from ericperez.info/api to heroku? That is NOT in place on your site at present, if you meant it (and you can see this in the deploy summary - example from current deploy at https://app.netlify.com/sites/musing-shockley-e29a8b/deploys/5f7d0160ad47fd0086ae19af shows none, so perhaps that’s all that is missing?