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
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 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.
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');
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.
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.
i got the solution i have change the endpoint of API
before i call like this:
http://localhost:8080/api/create/
now, i just remove the shash '/'
http://localhost:8080/api/create
it's working on my production server
The cors (Cross-Origin Resource Sharing) handle by server side. If you are come from laravel end so the barryvdh/laravel-cors package is help to solve this error
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
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? .
Pay close attention to the OPTIONS
method, since this enables the support for Preflight.
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
禁用此标志对我有用:chrome://flags/#block-insecure-private-network-requests
nelmio_cors: 默认值: allow_origin: [" "] allow_headers: [" "] allow_methods: ["POST", "PUT", "GET", "DELETE", "OPTIONS"] max_age: 3600 origin_regex: 错误路径: '^/ ': ~ 添加 nelmio_cors /packge/nelmio_cors
Steps
Go to this link https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf
download it
switch on the chrome web browser extension
Check your http link
example http to https of the remote url. do the get api.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.