0

I am making a small project in Vue3 using the recommended dev server setup http://localhost:5173. The files are all on a linux apache web server in /var/www/html/etc.. but php scripts won't run from within localhost:5173.

When I try to access the php files directly :

await fetch('http://localhost/vue-project/src/php/test.php', {method: 'GET'})

I get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

Can anyone help me with a solution to this please?

Alex
  • 79
  • 7
  • 1
    Your PHP scripts need to set CORS headers. https://enable-cors.org/server_php.html – ceejayoz Jan 04 '23 at 15:00
  • That's amazing thank you. I will post the answer to my question in full when I have figured out what to do for the build stage, which I don't think would be very difficult. – Alex Jan 04 '23 at 16:04
  • ..but it still doesn't work when I try to do fetch using POST – Alex Jan 04 '23 at 16:58

1 Answers1

0

I found a solution here: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at url

..is to access the php script using the full url (http://localhost/etc...) and to put the following lines of code at the top of any php script:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Because this is just for the purposes of getting the php to work whilst 'npm run dev', after 'npm run build' you could then remove those lines of code and just change the javascript to reference the php files directly.

Any other recommendations would be welcome.

Alex
  • 79
  • 7