简体   繁体   English

从前端到后端的CORS策略阻止请求

[英]CORS policy blocking request from frontend to backend

I am developing an application in vuejs. 我正在vuejs中开发应用程序。 I need to show some charts on the UI, for this I am requesting my backend for the data, but the request is getting blocked due to CORS policy. 我需要在UI上显示一些图表,为此,我正在向后端请求数据,但是由于CORS策略,该请求被阻止了。 I am using axios to make the request to backend. 我正在使用axios向后端提出请求。 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> 

I have enabled the CORS middleware in backend. 我已经在后端启用了CORS中间件。 My app.js file 我的app.js文件

 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; 

You configured the cors module like this: 您像这样配置cors模块:

 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. 当然, Access-Control-Allow-Origin是一个响应标头,因此它不应该放在请求的首位。 Remove that. 删除它。

I searched in Github, there is exists a solution with setting crossdomain in axios const config = {headers: {'Access-Control-Allow-Origin': '*'}}; 我在Github中搜索,存在一种在axios const config = {headers: {'Access-Control-Allow-Origin': '*'}};设置跨域的解决方案const config = {headers: {'Access-Control-Allow-Origin': '*'}}; need to replace with { crossdomain: true } 需要替换为{ crossdomain: true }

Here is a link to the answer: https://github.com/axios/axios/issues/853#issuecomment-322954804 这是答案的链接: https : //github.com/axios/axios/issues/853#issuecomment-322954804

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM