Home > Software engineering >  PHP Cors Errors
PHP Cors Errors

Time:08-12

I brought the project that I wrote in local with vue, but I cannot send a request to the api running on the same server. It crashes into a cors error. The backend is written in php.

//header("Access-Control-Allow-Origin: *"); Such codes could not be deciphered.

CodePudding user response:

Please add this code block to your head of the page

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json; charset=utf-8');

CodePudding user response:

In order to debug this issue you need to understand what CORS really is and why it's needed. In short, its a security mechanism implemented by browsers to prevent malicious requests on a server (I hope I explained it properly). Adding the header information at the backend sometime does not entirely help.

The browser is preventing your request because your frontend is running on http://localhost:3000/ and the backend services usually runs on http://localhost:80/ or http://localhost:8080/. That's two totally different origins to the browser due to ports. The browsers also send a preflight request to ensure the correct origin. I only have these possible fixes for you since you didn't post any project's (frontend or backend) configurations or network request and response logs.

  1. You can deploy your backend and frontend on a hosting, that way your requesting and receiving ends will be the same.
  2. You can set the header('Access-Control-Allow-Origin: *') in php and create a file in your Vue.js project's root directory by the name of vue.config.js and insert the below code to configure a proxy (assuming you're using Vue3):
    module.exports = {
        devServer: {
            port: 80, // or your backend port
            proxy: 'http://localhost:80/' // or your backend url
        }
    };

Allowing all origins is NOT a good idea!

  1. You can install a plugin in your browser to disable the CORS check by the brower (Not a recommend way, but could be handy when just trying to run your app).

Note: Please try to provide as much details to your question as you can it can help the community to debug your problem!

  • Related