• node与vue结合的前后端分离跨域问题


    第一点:node作为服务端提供数据接口,vue使用axios访问接口,

    安装axios

    npm install axios --save

    安装完成后在main.js中增加一下配置:

    import axios from 'axios';
    axios.defaults.withCredentials=true
    Vue.prototype.$axios = axios;

    main.js全部配置如下:

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    
    import axios from 'axios';
    axios.defaults.withCredentials=true;
    Vue.prototype.$axios = axios;
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      template: '<App/>',
      components: { App }
    })

    withCredentials默认是false,意思就是不携带cookie信息,那就让它为true,我是全局性配置的,就是main.js中的这句话:

    axios.defaults.withCredentials=true;

    得到数据有两种方式:

    第一种Get请求,写法为

    (1)不传递参数

    this.$axios.get("远程服务地址URL",{
            withCredentials : true//可以带cookie的认证
                 }).then(function(res){
    //对返回的数据res进行处理的逻辑 })

     (2)传递参数 需要params

    this.$axios.get("远程服务地址URL",params:{
      key1:value1
    },{
       withCredentials : true//可以带cookie的认证
         }).then(function(res){
    
    /对返回的数据res进行处理的逻辑
    
    })

     node后台接受访问获取参数的方式为:query

    router.get('/addressList', function (req, res, next) {
       var    key1= req.query.key1;
        User.findOne({key1: key1}, function (err, doc) {
            if (err) {
                res.json({
                    status: "1",
                    msg: err.message,
                    result: ''
                });
            } else {
                res.json({
                    status: "0",
                    msg: '',
                    result: {
    
                })
            }
        })
    });

    第二种Post请求:此处一定要对传递的参数进行一次转型,否则报错,使用插件qs(自身携带,引用即可)需要使用的地方使用import直接导入  import  qs from 'qs'

     this.$axios.post("远程URL", qs.stringify({ke12:value2},{
                      withCredentials : true
                    })).then(function(res){
    
                   //对返回的数据res进行处理的逻辑
                           })

    node后台获取值为:body

    router.post('/delAddress', function (req, res, next) {
    
        var key1= req.body.key1;
       
    });

    以上是属于客户端的针对可以访问远程的配置,要想成功还需服务端的配置,共同配合使用,否则无效任然报错。

    在服务端我们需要在app.js中全局配置

    //设置跨域访问
    var express=require('express')
    var app=express()
    app.all('*', function (req, res, next) { res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); res.header("Access-Control-Allow-Credentials", "true"); res.header("Access-Control-Allow-Origin", "此处是你的客户端的Url"); if (req.method == 'OPTIONS') { /*让options请求快速返回*/ res.send(200); } else { next(); } });

    需要让axios请求携带cookie,也就是认证信息,于是在后台拦截器中(app.js中),增加了一个需要认证信息的header:

    res.header("Access-Control-Allow-Credentials", "true");

    然后再次在浏览器中测试,发现浏览器提示,当Access-Control-Allow-Credentials设为true的时候,Access-Control-Allow-Origin不能设为星号,既然不让我设为星号,我就改成前端项目的配置

    res.header("Access-Control-Allow-Origin", http://127.0.0.1:8081);

    注意:使用顺序,请按照上述的代码顺序依次引入,否则任有可能报错。上述的全局配置中其实会出现异步请求问题,也就是"重复作出响应"问题----Error: Can't set headers after they are sent

    所以配置应改成:

    app.all('*', function (req, res, next) {
        res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
        res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Credentials", "true");
        res.header("Access-Control-Allow-Origin", "http://localhost:8081");//配置客户端 localhost与127.0.0.1是一个意思
        if (req.method == 'OPTIONS') {
            /*让options请求快速返回*/
            res.send(200);
        }
        else {
    /*防止异步造成多次响应,出现错误*/
            var _send = res.send;
            var sent = false;
            res.send = function (data) {
                if (sent) return;
                _send.bind(res)(data);
                sent = true;
            };
            next();
        }
    });
  • 相关阅读:
    python中list的一种取值方式切片
    python之字典(Dictionary)
    表示数字
    自动收售货系统
    明明的随机数
    自守数
    等差数列
    计算字符个数
    字符统计
    Redraimen的走法
  • 原文地址:https://www.cnblogs.com/wfaceboss/p/7893691.html
Copyright © 2020-2023  润新知