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?