0
votes

I'm having a very tough time getting started with Google Cloud functions. In specific, making a simple HTTP POST Request.

The Cloud Function looks like this:

const express = require('express')
const errorhandler = require('errorhandler')
const logger = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')

let app = express()

app.use(bodyParser.json())
app.use(logger('dev'))
app.use(errorhandler())
app.use(cors({origin: true}))

exports.helloWorld = (req, res) => {
  // Example input: {"message": "Hello!"}
  if (req.body.message === undefined) {
    // This is an error case, as "message" is required.
    res.status(400).send('No message defined!');
  } else {
    // Everything is okay.
    console.log(req.body.message);
    res.status(200).send('Success: ' + req.body.message);
  }
};

I'm making the HTTP Request from a simple form HTML file, and a JS file that looks like:

const sendMessage = () => {



    const input = {
        "message" : document.getElementById('message').value
    }


    fetch('https://google-cloud-url-endpoint', {
        method: 'POST',
        headers: { "Content-Type": "application/json"},
        body: JSON.stringify(input)
    }).then(function(response) {
        return response.json()
    }).then(function(data) {

    })
}

After typing in a message in the HTML Form, the console says:

OPTIONS https://https://google-cloud-url-endpoint 400 () index.html:1 Failed to load https://google-cloud-url-endpoint: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:53922' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. index.html:1 Uncaught (in promise) TypeError: Failed to fetch

When inspecting the Network Response, I see:

No message defined!

So from what I understand, it's making the request and bringing a response from the function. My question is, how come it's not successfully sending the 'message' to the function?

1
Update: On this app called Postman, I set the request to POST, entered the URL, and defined {"message":"Hello There!"} and it successfully posted via the app.....I copied the code straight from the app and put it in my js file and it still says the same thing!Carole

1 Answers

1
votes

SOLUTION:

Here's my client JS code:

function sendMessage() {

var message = document.getElementById('message').value

var data = JSON.stringify({
  "message": message
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://us-central1-stripe- 
update.cloudfunctions.net/function-1");
xhr.setRequestHeader("Content-Type", "application/json");


xhr.send(data);
}

Here's The Google Cloud Functions code:

exports.helloWorld = (req, res) => {
  // Example input: {"message": "Hello!"}

  //set JSON content type and CORS headers for the response
    res.header('Content-Type','application/json');
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials', 'true');

    //respond to CORS preflight requests
    if (req.method == 'OPTIONS') {
        res.status(204).send('');
    }

  if (req.body.message === undefined) {
    // This is an error case, as "message" is required.
    res.status(400).send('No message defined!');
  } else {
    // Everything is okay.
    console.log(req.body.message);
    res.status(200).send('Success: ' + req.body.message);
  }
};