【问题标题】:Failing HTTP "Post" Request from GitHub Pages来自 GitHub 页面的 HTTP“发布”请求失败
【发布时间】: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


【解决方案1】:

了解GitHub Pages 发布您推送到存储库的所有静态文件非常重要。它也很想注意到...

GitHub Pages 不支持服务器端语言,例如nodejs、python等

由于POST 请求需要服务器端通信,因此您需要获取一个实际的服务器主机。
Here's a good read about Static sites by GitHub Pages

【讨论】:

  • 谢谢!不过,我找到了解决问题的方法。我正在发送带有 wufoo 表单的发布请求。效果很好!
  • 它是否扩展了 GitHub Pages 以在服务器端工作?请分享“wufoo”的链接。我也想了解它是如何工作的。谢谢。
  • 是的,这里是link。您每月可以填写 100 份表格,这足以满足我的需求。创建表单后,您可以选择下载该表单的 html、css 和 javascript。您现在可以使用代码并将其集成到您的网站中。
猜你喜欢
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多