В настоящее время я создаю свой собственный веб-сайт, размещенный на GitHub Pages
.
Приложение построено с react.js
, и здесь показана форма для связи. Проблема, с которой я сталкиваюсь, заключается в том, что я не могу отправить запрос POST на google cloud platform
с помощью службы облачных функций через форму на GitHub pages
.
Я уверен, что код node.js
на GCP работает, так как я использовал Postman
для отправки запроса.
С журналом GCP функция может анализировать 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();
}
})
}
Вот что на 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: 'example@gmail.com',
from: { email: jsonBody.email, name: jsonBody.name },
subject: jsonBody.subject,
text: jsonBody.msg
};
sgMail.send(msg);
res.send("received!");
res.end();
};