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();
    }
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM