link137 link138 link139 link140 link141 link142 link143 link144 link145 link146 link147 link148 link149 link150 link151 link152 link153 link154 link155 link156 link157 link158 link159 link160 link161 link162 link163 link164 link165 link166 link167 link168 link169 link170 link171 link172 link173 link174 link175 link176 link177 link178 link179 link180 link181 link182 link183 link184 link185 link186 link187 link188 link189 link190 link191 link192 link193 link194 link195 link196 link197 link198 link199 link200 link201 link202 link203 link204 link205 link206 link207 link208 link209 link210 link211 link212 link213 link214 link215 link216 link217 link218 link219 link220 link221 link222 link223 link224 link225 link226 link227 link228 link229 link230 link231 link232 link233 link234 link235 link236 link237 link238 link239 link240 link241 link242 link243 link244 link245 link246 link247 link248 link249 link250 link251 link252 link253 link254 link255 link256 link257 link258 link259 link260 link261 link262 link263 link264 link265 link266 link267 link268 link269 link270 link271 link272 link273

[Vue.js] CORS policy blocking request from frontend to backend

when developing an application in vuejs. I need to show some charts on the UI, for this when requesting my backend for the data, but the request is getting blocked due to CORS policy. when using axios to make the request to backend. Here is my chart component which is making the call

<template>
<div class=”filed-against-chart” ref=”chartdiv” id=”filedAgainstChart”>
</div>
</template>

<script>
import axios from ‘axios’;
import * as am4core from “@amcharts/amcharts4/core”;
import * as am4charts from “@amcharts/amcharts4/charts”;
import am4themes_animated from “@amcharts/amcharts4/themes/animated”;
am4core.useTheme(am4themes_animated);

export default {
name: ‘FiledAgainstChart’,
mounted() {
const config = {headers: {‘Access-Control-Allow-Origin’: ‘*‘};
axios
.get(‘http://localhost:3000/ticket/filedagainst', config)
.then(response => this.chart.data = response);

let chart = am4core.create(‘filedAgainstChart’, am4charts.PieChart);
chart.hiddenState.properties.opacity = 0; // this creates initial fade-in

chart.data = [];
chart.radius = am4core.percent(70);
chart.innerRadius = am4core.percent(40);
chart.startAngle = 180;
chart.endAngle = 360;

let series = chart.series.push(new am4charts.PieSeries());
series.dataFields.value = “value”;
series.dataFields.category = “key”;

series.slices.template.cornerRadius = 10;
series.slices.template.innerCornerRadius = 7;
series.slices.template.draggable = true;
series.slices.template.inert = true;
series.alignLabels = false;

series.hiddenState.properties.startAngle = 90;
series.hiddenState.properties.endAngle = 90;

chart.legend = new am4charts.Legend();

}
}
</script>

<style scoped>
.filed-against-chart {
width: 100%;
height: 400px;
}
</style>

there is enabled the CORS middleware in backend.
My app.js file

const createError = require(‘http-errors’);
const express = require(‘express’);
const path = require(‘path’);
const cookieParser = require(‘cookie-parser’);
const logger = require(‘morgan’);
const cors = require(‘cors’);

const ticketRouter = require(‘./routes/ticket’);

const app = express();

// view engine setup
app.set(‘views’, path.join(__dirname, ‘views’));
app.set(‘view engine’, ‘pug’);

app.use(cors());

app.use(logger(‘dev’));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, ‘public’)));

app.use(‘/ticket’, ticketRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get(‘env’) === ‘development’ ? err : {};

// render the error page
res.status(err.status || 500);
res.render(‘error’);
});

module.exports = app;
My router file

Here is my router

const express = require(‘express’);
const router = express.Router();
const ticketTable = require(‘../controllers/ticketTable’);
const cors = require(‘cors’);

router.get(‘/‘, async function (req, res, next) {
const data = await ticketTable.getAllData();
res.send(JSON.stringify(data));
});

router.get(‘/filedagainst’, cors({origin: ‘http://localhost:3000/ticket/filedagainst'}), async function (req, res, next) {
const data = await ticketTable.getFiledAgainstChartData();
res.send(JSON.stringify(data));
});

module.exports = router;

Solution :

You configured the cors module like this:

app.use(cors());

but that only allows for simple requests.

See the documentation for how to support preflighted requests.

Note, that you wouldn’t be making a preflighted request if it wasn’t for this:

const config = {headers: {‘Access-Control-Allow-Origin’: ‘*‘};

custom request headers require a preflight. Of course, Access-Control-Allow-Origin is a response header so it shouldn’t be on the request in the first place. Remove that.

Solution 2:

I searched in Github, there is exists a solution with setting crossdomain in axios
const config = {headers: {‘Access-Control-Allow-Origin’: ‘*‘}; need to replace with { crossdomain: true }

Here is a link to the answer: https://github.com/axios/axios/issues/853#issuecomment-322954804