【发布时间】:2020-07-08 20:19:47
【问题描述】:
我目前正在构建自己的网站,该网站托管在 GitHub Pages。
该应用是使用react.js 构建的,此处显示的是联系表格。
我遇到的问题是我无法通过GitHub pages 上的表单使用云功能服务向google cloud platform 发送POST 请求。
我确信 GCP 上的 node.js 代码可以正常工作,因为我使用 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();
};
【问题讨论】:
-
如果某些东西不起作用,那么分享症状是一个非常好的主意。发生了什么?您的控制台中是否出现错误?
-
已编辑帖子!
-
你传递的是一个字符串给 fetch(),而不是一个 url。
-
我使用 GCP_API_HTTP 向 GCP 隐藏了我的 HTTP 触发器。但真正的实现是一个 URL
-
我的第一个猜测是您的内容类型不完全是
application/json。您能否 console.log(服务器端)req.get('Content-Type')和req.body
标签: node.js reactjs post google-cloud-platform github-pages