Home > Back-end >  How to allow CORS in Yii2?
How to allow CORS in Yii2?

Time:09-25

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.

CodePudding user response:

Yii2 supports CORS handling, as written on the official documentation.

public function behaviors()
{
    return [
        'corsFilter' => [
            'class' => \yii\filters\Cors::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

  • Related