Since I have access to the shared hosting, which doesn't have node installed, I cannot use express as a server (or any of the fancy node stuff xD).
Now, the reason why I need a server is basically because when I fetch data from Behance API from my app I'm get a CORS error.
So the idea is to have a server.php
which fetches the details from the 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;
I've tested this locally, and I get the correct JSON back (opening localhost/server.php
- I'm on mac and have php 7.1 set up locally).
Now what I'm interested in is: how to use this in my React app?
Do I just then do a fetch()
towards https://mysite/server.php
and that's it?
I tried by setting the fetch url to http://localhost/server.php
but I still get the CORS error
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.
My guess is the port part is the fault.
The fetching part looks like:
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);
}
How do I make this work locally?