I have a JavaScript frontend that ask for a plain text to my PHP backend.
It almost works excepts because I have a CORS problem. How can allow CORS in my PHP code?
My frontend (JavaScript and jQuery):
$.ajax({ type: 'GET', url: 'http://localhost:8080/', }) .done(function(data) { console.log(data); }) .fail(function() { alert("Oh, no. CORS error again."); });
My backend (PHP and Yii2):
$result = file_get_contents('http://m2m.exemys.com/...'); // This URL is a bit larger with more parameters. var_dump($result); // Plain text. Just some characters.
Advertisement
Answer
Yii2 supports CORS handling, as written on the official documentation.
public function behaviors() { return [ 'corsFilter' => [ 'class' => yiifiltersCors::class, ], ]; }
Alternatively, you could try adding the following headers on your PHP backend:
<?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: *');
If doesn’t work, take a look at https://stackoverflow.com/a/9866124/11591212