Search code examples
node.jsreactjspostgoogle-cloud-platformgithub-pages

Failing HTTP "Post" Request from GitHub Pages


I'm currently building my own website that is hosted on GitHub Pages.

The app is built with react.js and what is shown here is a contact form.
The problem I'm encountering is that I cannot send a POST request to a google cloud platform with the cloud function service through the form on the GitHub pages.

Am sure the node.js code on GCP is working since i've used Postman to send a request.

With the GCP log, the function is able to parse the POST:

// react code
submitForm(event) {
  const {name, email, subject, message} = this.state;
  console.log("sending email...");
  console.log(JSON.stringify({name: name, email: email, subject: subject, msg: message}));
  fetch('GCP_API_HTTP', {
    method: 'POST',
    headers: { 'content-type': 'application/json', },
    body: JSON.stringify({ name: name, email: email, subject: subject, msg: message })
   }).then((response) => {
      if (response.status === 200) {
         return response.text();
      } else {
         this.setState({emailError: true});
         return response.text();
      }
   })
}

Here's what's on GCP:

// GCP
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey('API_KEY');

exports.contactMe = (req, res)=> {
  let jsonBody;

  switch (req.get('Content-Type')) {
    // '{"name":"John"}'
    case 'application/json':
      jsonBody = req.body;
      break;
    // 'John'
    case 'text/plain':
      jsonBody = req.body;
      break;
    // 'name=John' in the body of a POST request (not the URL)
    case 'application/x-www-form-urlencoded':
      jsonBody = req.body;
      break;
  }

  let msg = {
        to: '[email protected]',
        from: { email: jsonBody.email, name: jsonBody.name },
        subject: jsonBody.subject,
        text: jsonBody.msg
    };
    sgMail.send(msg);
    res.send("received!");
    res.end();
};

Solution

  • It is quite critical to understand that GitHub Pages publishes any static files that you push to your repository. And it's also keen to note that...

    GitHub Pages does not support server-side languages e.g. nodejs, python etc.

    Since POST requests require server-side communication, you'll need to get an actual server host.
    Here's a good read about Static sites by GitHub Pages