【问题标题】:PHP to Typescript conversionPHP 到 Typescript 的转换
【发布时间】:2021-09-30 04:39:45
【问题描述】:

我正在尝试为 firebase 构建一个函数,以通过 POST 方法调用命令上的 url。我目前已经很好地实现了 GET 方法,但是 POST 方法让我摸不着头脑。

我有一些通过 fetch 调用的示例代码,但我不确定下面这个 sn-p 中的参数需要去哪里:

<?php

$url = 'https://profootballapi.com/schedule';

$api_key = '__YOUR__API__KEY__';

$query_string = 'api_key='.$api_key.'&year=2014&week=7&season_type=REG';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$result = curl_exec($ch);

curl_close($ch);

echo $result;

?> 

我的 POST 请求示例代码如下所示:

const apiKey = "myAPIkey";
const url = "https://profootballapi.com/schedule";
const response = await fetch(url, {
  method: 'POST',
  body: 'api_key'= apiKey, '&year=2018&week=7&season_typeRG';
  headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}});

if (!response.ok) {/* Handle */}

  // If you care about a response:
  if (response.body !== null) {
    functions.logger.log(response.body); 
  }

【问题讨论】:

  • 我认为这是一个寻求调试帮助的公平问题,但我认为标题会引起消极情绪。经常看到诸如“有人可以帮我转换这段代码吗?”之类的帖子。键入提问者不费力的问题。我很高兴看到您尝试自行转换它。我想不出更好的标题:-)
  • 感谢您的反馈,长时间的听众,第一次来电大声笑。我会记住的!

标签: php typescript firebase google-cloud-functions


【解决方案1】:

你已经很接近了。你的 TypeScript 中只是有一些语法级别的问题:

curl_setopt($ch, CURLOPT_URL, $url);

您正确传递了网址。

curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);

这只是为请求提供 HTTP 正文 您已经在 fetch 中尝试过此操作,但存在一些语法问题。你应该用这个替换body

body: `api_key=${apiKey}&year=2018&week=7&season_type=REG`
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

这是免费的。 fetch 自动返回response 中的响应。

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

假设此代码将在浏览器上运行,您将无法禁用它。它告诉客户端验证服务器的 SSL 证书。如果你能提供帮助,你应该避免禁用它。

我测试了这段代码,在 Chrome 的调试工具中得到了一些合理的结果:

const foo = async function () {
  const apiKey = "myAPIkey";
  const url = "https://profootballapi.com/schedule";
  const response = await fetch(url, {
    method: 'POST',
    body: `api_key=${apiKey}&year=2018&week=7&season_type=REG`,
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
  });

  return response;
}

foo().then(response => console.log(response));

它会产生 500 错误,但我怀疑这与没有有效的 API 密钥有关。如何提交有效的 API 请求就交给你了。

【讨论】:

  • 您不应该使用串联构建 POST 参数字符串。使用正确编码字符的专用方法。例如,在 PHP 中,这将是 http_build_query
  • 太棒了!非常感谢,我想我已经很接近了,但不确定正文所需的语法。
猜你喜欢
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 2014-07-13
  • 2011-02-26
  • 1970-01-01
相关资源
最近更新 更多