javascript - 使用 PHP 脚本作为 React 应用程序的 'server'?

标签 javascript php reactjs server

因为我可以访问没有安装节点的共享主机,所以我不能将 express 用作服务器(或任何花哨的节点东西 xD)。

现在,我需要服务器的原因基本上是因为当我从我的应用程序的 Behance API 获取数据时,我收到了 CORS 错误。

所以我们的想法是有一个 server.php 从 Behance API 中获取详细信息

<?php

$endpoint = ( isset( $_GET['project'] ) ) ? "projects/{$_GET['project']}" : 'projects';

$api_key = '**************';
$url     = "https://behance.net/v2/users/myuser/{$endpoint}?api_key={$api_key}";

$contents = file_get_contents( $url );

echo $contents;

我已经在本地测试过了,我得到了正确的 JSON(打开 localhost/server.php - 我在 mac 上,并在本地设置了 php 7.1)。

现在我感兴趣的是:如何在我的 React 应用程序中使用它?

然后我对 https://mysite/server.php 执行 fetch() 就可以了吗?

我尝试将获取 url 设置为 http://localhost/server.php 但我仍然收到 CORS 错误

Failed to load http://localhost/server.php?project=: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我的猜测是端口部分有问题。

获取部分如下所示:

const fetchData = async (endpoint, method, headers, body) => {
  const options = {};

  options.method = method;
  options.headers = headers || {};

  if (typeof body !== 'undefined') {
    options.body = JSON.stringify(body);
  }

  const url = `http://localhost/server.php?project=${endpoint}`;

  return fetch(url, options).then((response) => response.json());
};

export function getItems() {
  const headers = {
    Accept: 'application/json;charset=utf-8',
    'Content-Type': 'application/json;charset=utf-8',
  };

  return fetchData('', 'GET', headers);
}

export function getItem(id) {
  const headers = {
    Accept: 'application/json;charset=utf-8',
    'Content-Type': 'application/json;charset=utf-8',
  };

  return fetchData(id, 'GET', headers);
}

我如何在本地进行这项工作?

最佳答案

因此,至少对于本地开发而言,答案是将 header() 添加到脚本中

<?php

header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Headers: Content-Type' );

$endpoint = ( isset( $_GET['project'] ) ) ? "projects/{$_GET['project']}" : 'projects';

$api_key = '**************';
$url     = "https://behance.net/v2/users/myuser/{$endpoint}?api_key={$api_key}";

$contents = file_get_contents( $url );

echo $contents;

我需要对其进行更多润色,但这确实有效 :)

关于javascript - 使用 PHP 脚本作为 React 应用程序的 'server'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49637931/

相关文章:

php - Jquery使用php var并暂停

php - 无法选中 <div> 内的复选框,但在外部运行良好

javascript - 将全局样式表移动到 <head> 中的样式组件之上

css - 你如何使用 React 在悬停时渲染不同的 SVG

javascript - 拉动刷新不在特定屏幕上禁用(React js)

php - 通知: Array to string conversion with update statment

javascript - 将 DRY 原则应用于此 jQuery 代码

reactjs - 从react js中的onClick事件获取对象数据和目标元素

javascript - 此代码返回 301 永久移动,而同一脚本正常工作

javascript - 离线应用程序中的 Backbone.js