1. 程式人生 > >vue+node.js跨域問題的解決

vue+node.js跨域問題的解決

vue預設是執行在localhost:8080上,而node.js可能執行在其他埠,而前臺去請求後臺的api時就存在跨域問題。

另外,我們經常會去訪問其他網站的資料,比如http://google.com/...,此時也存在跨域問題。

解決跨域問題的方法:

利用vue-cli自帶的解決跨域的問題

1.在config/index.js中利用proxy代理的方法

dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    //開啟代理伺服器,解決跨域問題
    proxyTable: {
        '/api': {
            target: 'http://localhost:8088',//要訪問的後端介面
            changeOrigin: true,
            pathRewrite: {
              '^/api': '/'
              //這裡的配置是正則表示式,以/api開頭的將會被用用‘/api'替換掉,假如後臺文件的介面是 /api/list/xxx      
              //前端api介面寫:axios.get('/api/list/xxx') , 被處理之後實際訪問的是:http://news.baidu.com/api/list/xxx 
            }
        }
    },

後臺的介面資料:

// 註冊
router.post('/api/user/register',(req,res) => {
   const _user = req.body;
   const userName = _user.userName;
   User.findOne({userName:userName},(err,user) =>{
        if(err){
            global.logger.error(err)
        }
        if(user){
            res.json({
                errno:1,
                data:'使用者名稱已經存在'
            })
        }else{
            //不存在使用者則建立新使用者並儲存到資料庫中
            user = new User(_user);
            user.save((err,user) =>{
                if(err){
                    global.logger.error(err);
                }
                res.json({
                    errno:0,
                    data:'註冊成功'
                })
            })
        }
   })
});

前臺呼叫後臺介面資料:

import axios from 'axios'
axios.get('/api/user/register',data).then(res=>{
	console.log(res);
}).catch(reject=>{
	console.log(reject);
})