因为我可以访问没有安装节点的共享主机,所以我不能将 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/