由于我可以访问没有安装节点的共享主机,所以不能使用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,并得到了正确的JSON(打开localhost/server.php -我在mac上,并在本地安装了php7.1)。
现在我感兴趣的是:如何在我的React应用程序中使用这个?
我是不是只是对fetch()做了一个https://mysite/server.php,就这样?
我尝试将fetch url设置为http://localhost/server.php,但仍然得到CORS错误
未能加载http://localhost/server.php?project=:对飞行前请求的响应没有通过访问控制检查:请求的资源上没有“访问控制-允许-原产地”标题。因此,“http://localhost:3000”源是不允许访问的。如果不透明响应满足您的需要,请将请求的模式设置为“no- CORS”,以获取禁用CORS的资源。
我猜端口部分是错的。
抓取部分如下所示:
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);
}我怎样才能让这个在本地发挥作用?
发布于 2018-04-03 20:11:15
所以,至少对于本地开发来说,答案是在脚本中添加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;我需要对它进行更多的润色,但这样做的关键是:)
https://stackoverflow.com/questions/49637931
复制相似问题