Javascript 如何修复“对 XMLHttpRequest 的访问已被 CORS 策略阻止”的预检请求不允许重定向,只有一个路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54212220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:12:53  来源:igfitidea点击:

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

javascriptlaravelvue.jsvuejs2

提问by priyeshvadhiya

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

在此处输入图片说明在此处输入图片说明我正在设置一个 Laravel 和 vuejs。

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

Laravel 和前端的 CORS 插件我使用 Axios 调用 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.

我收到此错误访问 XMLHttpRequest at ' https://xx.xxxx.xx' from origin ' http://localhost:8080' has been Blockedby CORS policy: Response to preflight request does not pass access control check: Redirect不允许用于预检请求。

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

错误仅发生在一条路线上,其余所有路线都在工作。也在Postman 上工作

回答by Md Riadul Islam

Disabling CORS policy security:

禁用 CORS 策略安全:

  1. Go to google extension and search for Allow-Control-Allow-Origin.
  2. Now add it to chrome and enable.
  3. Add https://localhostto 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.exefile 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.

  1. 转到 google 扩展程序并搜索Allow-Control-Allow-Origin
  2. 现在将其添加到 chrome 并启用。
  3. https://localhost添加到它的设置中,如屏幕截图:

    在此处输入图片说明

  4. 现在关闭所有 chrome 浏览器并打开 cmd。然后运行以下命令:

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

    如果命令运行正常,您将看到如下图所示的通知:

    在此处输入图片说明

    如果您看不到通知,则该命令无效。所以你应该检查命令中指定的目录链接,以确保该目录链接中存在 chrome.exe 文件。如果您找到该chrome.exe文件,则在关闭 chrome 浏览器后,您应该检查任务管理器是否有任何其他 chrome 服务在后台运行。关闭所有服务后,该命令应按预期工作。

Internet Explorer:

IE浏览器:

  1. To disable cors policy in internet explorer please go to internet option > security > Internetand 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

  1. 要在 Internet Explorer 中禁用 cors 策略,请转到internet option > security > Internet并取消选中启用保护模式。
  2. 然后单击自定义级别并在杂项下启用跨域访问数据源,如下图所示。对 执行相同的过程internet option > security > Local intranet

    在此处输入图片说明

Hope it will solve your problem.

希望它能解决你的问题。

回答by Ali Mohammed

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

问题来自后端,在我们的案例中是 Laravel,在您的 config/cors.php 中尝试使用以下配置:

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

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

或者你可以尝试在 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');

回答by Sublime Laravel Dev

The cors (Cross-Origin Resource Sharing) handle by server side. If you are come from laravel end so the barryvdh/laravel-corspackage is help to solve this error

cors(跨域资源共享)由服务器端处理。如果您来自 laravel 端,那么barryvdh/laravel-cors包有助于解决此错误

url: https://packagist.org/packages/barryvdh/laravel-cors

网址:https: //packagist.org/packages/barryvdh/laravel-cors

回答by tanvir993

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.

如果您将其用作 axios 请求的基本 url,我们可以使用 APP_URL 进行修复。请确保您的浏览器根 url 和 .env 中的 APP_URL 都相同。

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

例如,如果您在“ http://127.0.0.1:8000”上运行应用程序,那么应该是 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

如果您在“ http://localhost:8000”上运行应用程序,那么应该是 APP_URL= http://localhost:8000

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

希望,这会有所帮助!它已经用 laravel6.x 测试过

回答by mllnd

You probably have some misconfiguration either on the webserver side or Laravel side. Perhaps this solution might help you: Why isn't my nginx web server handling ttf fonts?.

您可能在 Web 服务器端或 Laravel 端有一些配置错误。也许这个解决方案可以帮助你:为什么我的 nginx web 服务器不处理 ttf 字体?.

Pay close attention to the OPTIONSmethod, since this enables the support for Preflight.

请密切注意该OPTIONS方法,因为这可以支持预检。