how to fix 'Access to XMLHttpRequest has been blocked by CORS policy' Redirect is not allowed for a preflight request only one route

218,689

Solution 1

Disabling CORS policy security:

  1. Go to google extension and search for Allow-Control-Allow-Origin.
  2. Now add it to chrome and enable.
  3. Add https://localhost to it’s setting like the screen shot:

    enter image description here

  4. Now close all your chrome browser and open cmd. Then run the followin command:

    “C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” –-allow-file-access-from-files --disable-web-security --user-data-dir --disable-features=CrossSiteDocumentBlockingIfIsolating

    If the command runs properly you will see the following notification like the below screenshot:

    enter image description here

    If you can’t see the notification then the command didn’t work. So you should check the directory link that have been specified in the command to ensure that the chrome.exe file exist in that directory link. If you find the chrome.exe file then after closing the chrome browser you should check the task manager if any other chrome service is running in background. After closing all the services the command should work as expected.

Internet Explorer:

  1. To disable cors policy in internet explorer please go to internet option > security > Internet and uncheck enable protected mode.
  2. Then click on custom level and enable Access data sources across domains under Miscellaneous like the below image. Follow the same process for internet option > security > Local intranet.

    enter image description here

Hope it will solve your problem.

Solution 2

The issue is from the back-end side in our case is Laravel, in your config/cors.php try to use the below config:

'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,

Or you can try to use this code in the top of public/index.php

Edit

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X- 
Request-With');

Solution 3

The problem comes from your Vue App.

Eg: You're requesting the url below:

https://example.com/api/methods/

And the backend redirect it to:

https://example.com/api/methods

Beware of the trailing slash at the end.

Solution 4

The problem is from the server side. If you are using express js. Try to install the express cors package on your server.

npm install cors

In your app.js require cors.

var cors = require('cors')

Then, add it as a middleware to your app.

app.use(cors())

You should not experience the cors issue after installing the package.

Solution 5

We can fix with APP_URL, if you use it as the base url for axios request. Please, make sure your browser root url and APP_URL in .env both are same.

For example, if you run the app on "http://127.0.0.1:8000" then should be the APP_URL=http://127.0.0.1:8000

And if you run the app on "http://localhost:8000" then should be the APP_URL=http://localhost:8000

Hope, this will help! And it's tested with laravel6.x

Share:
218,689

Related videos on Youtube

priyeshvadhiya
Author by

priyeshvadhiya

I am 25 year-old web developer from INDIA

Updated on March 05, 2022

Comments

  • priyeshvadhiya
    priyeshvadhiya about 2 years

    enter image description hereenter image description herei'm setting a laravel and vuejs.

    CORS plugin for laravel and frontend side i use Axios to call REST api

    i got this ERROR Access to XMLHttpRequest at 'https://xx.xxxx.xx' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

    this is for a vuejs axios setup  **main.js**
    axios.defaults.baseURL = process.env.BASE_URL;
    axios.defaults.headers.get['Accepts'] = 'application/json';
    axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
    axios.defaults.headers.common['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept';
    
      **content.vue file**
    
      this.loading = true;
          var companyId = this.$route.params.cid;
          var userId = this.$route.params.uid;
          const thisVue = this;
          var formData = new FormData();
    
      let data = {};
    
      formData.append("subject", this.title);
      formData.append("content", this.content);
      formData.append("posting_article_url", this.blog_link);
      formData.append("recruitment_tension", this.sel_recruitment_tension);
      formData.append("why_hire_engineer", this.sel_company_hire_engineer);
      formData.append("technique_skill", this.requiredTechniqueSkill);
      formData.append("better_technique_skill",this.betterTechniqueSkillIfThereIs);
      formData.append("personality", this.requiredPersonality);
      formData.append("any_request", this.anyRequest);
      formData.append("location", this.location);
      formData.append("supplement_time", this.supplement_time);
      formData.append("supplement_contract", this.supplement_contract);
      formData.append("en_benefits", this.en_benefits);
      formData.append("recruit_role", this.recruit_role);
      formData.append("how_to_proceed", this.how_to_proceed);
      formData.append("current_structure", this.current_structure);
      if (this.selectedSkill.length > 0)
      {
        let selectedSkills = this.selectedSkill
        .filter(obj => {
          return  obj.id;
        })
        .map(item => {
          return item.id;
        });
        formData.append("skill_keyword", selectedSkills);
      }
      if (this.imageBlob != "") {
        formData.append("image", this.imageBlob, "temp.png");
      }
      for (var i = 0; i < this.sel_schedule.length; i++) {
        formData.append("freelance_type[" + i + "]", this.sel_schedule[i])
      }
      for (var i = 0; i < this.sel_type_of_contract.length; i++) {
        formData.append("contract_type[" + i + "]", this.sel_type_of_contract[i])
      }
        this.loading = false;
        $('html, body').animate({scrollTop:300}, 'slow');
      } else {
         axios
        .post(
          "/xx/xxx/?token=" + localStorage.getItem("token"),
          formData,
          {
            headers: [
                { "X-localization": localStorage.getItem("lan") },
                { "Access-Control-Allow-Origin": '*' },
                { "Access-Control-Allow-Headers": 'Origin, X-Requested-With, Content-Type, Accept '},
                { "Access-Control-Allow-Methods": "POST, GET, PUT, OPTIONS, DELETE" },
                { "Access-Control-Max-Age": 3600 }
              ]
          }
        )
        .then(res => {
          if (!res.data.result) {
             if (res.data[0]) {
              this.$toaster.error(res.data[0]);
              this.$store.dispatch("logout");
            }
            if (res.data.errors) {
                for (var i = 0; i < res.data.errors.length; i++) {
                  this.$toaster.error(res.data.errors[i].message);
                }
            }
            this.loading = false;
          } else {
            this.$toaster.success(thisVue.$t("success_recruit_add"));
          }
        })
        .catch(() => {
          this.$toaster.error(thisVue.$t("err_network"));
        });
      }
    

    the error occur only one route rest all are working. also working on Postman

    • Ferrybig
      Ferrybig over 5 years
      Your error says a HTTP redirect is not allowed for the preflight OPTIONS request, you now need to debug why the other server is sending this
    • priyeshvadhiya
      priyeshvadhiya over 5 years
      @Ferrybig i got error only one route all other are working good and also running well on my local server.
    • Ferrybig
      Ferrybig over 5 years
      Could you show the full response, including the path of the original url, and the path of the url the server tries to redirect you
  • priyeshvadhiya
    priyeshvadhiya over 5 years
    still did't work, i change code what you are said but, still face same error.
  • priyeshvadhiya
    priyeshvadhiya over 5 years
    why its not working only one route? all other routes are working fine.
  • priyeshvadhiya
    priyeshvadhiya about 5 years
    great effort but, my scenario are different.
  • Md Riadul Islam
    Md Riadul Islam about 5 years
    What is your scenario ?
  • Ziaur Rahman
    Ziaur Rahman about 5 years
    it has solved my problem, I am facing this for several days
  • Olu Adeyemo
    Olu Adeyemo about 4 years
    This will solve the problem on the local machine. But when you go live, the problem persists. It is not a good solution to tell all your users to install an extension or do some settings on their browsers.
  • Md Riadul Islam
    Md Riadul Islam about 4 years
    @franc definitely it is not good for server. The solution is for localhost only. In server there are several best practices that you can follow. Here I am sharing one: w3.org/wiki/CORS_Enabled
  • Nithin Paul
    Nithin Paul over 3 years
    Can you explain from where is exactly opening that 3rd point - Add localhost to it’s setting like the screen shot: I am not to find that option
  • Denny
    Denny about 3 years
    The link is broken
  • ksugiarto
    ksugiarto almost 3 years
    I do agree with @franc this is not a good solution and should not be the accepted answer
  • Md Riadul Islam
    Md Riadul Islam almost 3 years
    @ksugiarto Could you please suggest a good solution for localhost ?? This solution is not good for server definitely, for server need to allow the url but in question the url is localhost so the answer should be based on local environment.
  • ksugiarto
    ksugiarto almost 3 years
    @MdRiadulIslam I am just passing by when searching for my own cors issue, I don't use vue.js. But here the thing, the problem with cors is always about the server, sometimes even we configure the cors correctly but the server response is not proper for that particular request, the front/browser could say it was a cors issue due to some missing cors configuration response from the server. Second, see how you hack the chrome with --disable-web-security, that is definitely something you did with your own risk, hence please don't suggest this risky solution.
  • ksugiarto
    ksugiarto almost 3 years
    Three, like the previous comment, when you change computer, OS, this will raise again when the real problem is the server. Not to mention the other team member if the author is working with, they will be easily replicate the case, furthermore, the goal of code always to run on the server, not localhost. In short, your solution may be working, but it is not a good solution yet.
  • Sanush
    Sanush about 2 years
    Same issue bro even after installing the cors module
  • Admin
    Admin about 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.