Node和Django中如何进行CORS跨域

28 篇文章 1 订阅
26 篇文章 1 订阅

一、Node服务端设置跨域:

1、axios不支持jsonp,因为axios的作者觉得jsonp不太友好,推荐用CORS方式更为干净;

2、在使用axios发送请求时,服务器端设置

res.header("Access-Control-Allow-Origin", "*")

可以正确得到结果。

3、实例:

3.1 node.js代码

let express = require("express");
let app = express();
 
app.use("/public", express.static("public"));
 
app.get("/index", function(req, res, next){
    res.sendFile(__dirname + "/" + "views/index.html");
});
 
app.get("/get_data", function(req, res, next){
	res.header("Access-Control-Allow-Origin", "*");
    let response = {
    	title: '在Vue中使用echarts',
    	xAxisData: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"],
    	seriesData: [10, 26, 16, 20, 16, 30]
    };
    res.type('application/json');
    res.jsonp(response);
});
 
app.listen(8000, function(){
    console.log("开始执行请求");
});

二、Python服务端设置跨域:

django代码:

settings.py中:

(1) 安装 django-cors-headers:

pip install django-cors-headers

(2) 添加到已安装的应用程序中:

INSTALLED_APPS  =(
     ... 
    ' corsheaders ',
     ... 
)

(3) 添加中间件类来收听响应:

MIDDLEWARE  = [
    ... 
    # 跨域请求中间件
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
     ... 
]

注意:要放在中间件(common.CommonMiddleware)的上面,涉及到请求响应的顺序问题。

(4) 跨域配置:

在settings文件最后面添加如下所有代码

# 跨域允许的请求方式,可以使用默认值,默认的请求方式为:
# from corsheaders.defaults import default_methods
CORS_ALLOW_METHODS = (
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS'
)

# 允许跨域的请求头,可以使用默认值,默认的请求头为:
# from corsheaders.defaults import default_headers
# CORS_ALLOW_HEADERS = default_headers

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

# 跨域请求时,是否运行携带cookie,默认为False
CORS_ALLOW_CREDENTIALS = True
# 允许所有主机执行跨站点请求,默认为False
# 如果没设置该参数,则必须设置白名单,运行部分白名单的主机才能执行跨站点请求
CORS_ORIGIN_ALLOW_ALL = True

echarts.vue代码:

<template>
  <div>
    <div id="myChart">

    </div>
  </div>
</template>

<script>
  export default {
    methods: {
      drawLine(){
        // 基于准备好的dom,初始化echarts实例
        let myChart = this.$echarts.init(document.getElementById('myChart'));

        this.$axios.get("http://127.0.0.1:8000/get_data")
          .then(function(res){
            // 绘制图表
            myChart.setOption({
              title: { text: res.data.title },
              tooltip: {},
              xAxis: {
                data: res.data.xAxisData
              },
              yAxis: {},
              series: [{
                name: '销量',
                type: 'bar',
                data: res.data.seriesData
              }]
            });
          })
          .catch(function(err){
            console.log(err);
          })
      }
    },
    mounted(){
      this.drawLine();
    }
  }
</script>

<style>
#myChart{
  height: 500px;
}
</style>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值