how to fix 'Access to XMLHttpRequest has been blocked by CORS policy' Redirect is not allowed for a preflight request only one route
Solution 1
Disabling CORS policy security:
- Go to google extension and search for Allow-Control-Allow-Origin.
- Now add it to chrome and enable.
-
Add https://localhost to it’s setting like the screen shot:
-
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:
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:
- To disable cors policy in internet explorer please go to
internet option > security > Internet
and uncheck enable protected mode. -
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
.
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
Related videos on Youtube
Comments
-
priyeshvadhiya about 2 years
i'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 over 5 yearsYour 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 over 5 years@Ferrybig i got error only one route all other are working good and also running well on my local server.
-
Ferrybig over 5 yearsCould 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 over 5 yearsstill did't work, i change code what you are said but, still face same error.
-
priyeshvadhiya over 5 yearswhy its not working only one route? all other routes are working fine.
-
priyeshvadhiya about 5 yearsgreat effort but, my scenario are different.
-
Md Riadul Islam about 5 yearsWhat is your scenario ?
-
Ziaur Rahman about 5 yearsit has solved my problem, I am facing this for several days
-
Olu Adeyemo about 4 yearsThis 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 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 over 3 yearsCan 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 about 3 yearsThe link is broken
-
ksugiarto almost 3 yearsI do agree with @franc this is not a good solution and should not be the accepted answer
-
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 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 almost 3 yearsThree, 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 about 2 yearsSame issue bro even after installing the cors module
-
Admin about 2 yearsYour 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.