В моем коде PHP в мой класс CoreMiddleware:
Код: Выделить всё
/**
* Middleware for handling CORS.
*
* @param Request $request the request object
* @param callable $next the next middleware to execute
* @return void
*/
public function handle(Request $request, callable $next) {
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;
return $next($request);
}
React Network Snapshot
Теперь, если я обращаюсь к API напрямую в веб-браузере, я получаю COR-заголовки. См. снимок ниже:
API PHP доступен непосредственно в снимке Chrome.
И ниже приведен код React для запроса данных из API:
Код: Выделить всё
/**
* Constructor that sets up this class.
*/
constructor() {
this.apiBaseUrl = process.env.REACT_APP_API_BASE_URL;
console.log(process.env);
this.client = axios.create({
baseURL: this.apiBaseUrl,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true
});
}
/**
* Gets data from the API.
* @param {string} endpoint the API endpoint
*/
getData(endpoint) {
return this.client.get(endpoint)
.then(response => response.data)
.catch(error => this.handleError(error));
}
Я попробовал добавить заголовки CORS в файл .htaccess, конфигурацию Apache. файл непосредственно через PHP. После этого я ожидал, что проблема с заголовком COR будет решена.
Подробнее здесь: https://stackoverflow.com/questions/788 ... quests-fro