node與vue結合的先後端分離跨域問題

第一點:node做爲服務端提供數據接口,vue使用axios訪問接口,前端

安裝axiosvue

npm install axios --save

安裝完成後在main.js中增長一下配置:node

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

 

main.js所有配置以下:ios

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中的這句話:express

axios.defaults.withCredentials=true;

獲得數據有兩種方式:npm

第一種Get請求,寫法爲json

(1)不傳遞參數axios

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();
    }
});
相關文章
相關標籤/搜索