【问题标题】:CORS policy blocking request from frontend to backend从前端到后端的 CORS 策略阻止请求
【发布时间】:2019-09-04 07:20:58
【问题描述】:

我正在用 vuejs 开发一个应用程序。我需要在 UI 上显示一些图表,为此我向我的后端请求数据,但由于 CORS 策略,该请求被阻止。我正在使用 axios 向后端发出请求。这是我正在调用的图表组件

<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>

我已在后端启用 CORS 中间件。 我的 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

这是我的路由器

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;

【问题讨论】:

    标签: javascript node.js express vue.js cors


    【解决方案1】:

    你像这样配置了 cors 模块:

    app.use(cors());
    

    ... 但这只允许 simple 请求。

    the documentation for how to support preflighted requests

    请注意,如果不是这样,您将不会发出预检请求:

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

    …自定义请求标头需要预检。当然,Access-Control-Allow-Origin 是一个 response 标头,因此它不应该首先出现在请求中。删除它。

    【讨论】:

      【解决方案2】:

      我在 Github 上搜索过,有一个在 axios 中设置跨域的解决方案 const config = {headers: {'Access-Control-Allow-Origin': '*'}};需要替换成{ crossdomain: true }

      这里是答案的链接:https://github.com/axios/axios/issues/853#issuecomment-322954804

      【讨论】:

      猜你喜欢
      • 2021-09-10
      • 2021-10-16
      • 2019-04-20
      • 2022-01-14
      • 2021-02-28
      • 2019-06-11
      • 2019-11-30
      • 2019-10-01
      • 2020-06-13
      相关资源
      最近更新 更多