Flutter for web 跨域請求解決方案

這裏使用nodejs服務器實現跨域,原理是flutter代碼直接跑到nodejs代理服務器上,這樣不用內部局域網跨域,然後通過代理對應用的請求進行轉發。

nodejs代碼:server.js

let http  = require('http')
let fs = require('fs')
let conifg = require('./proxy-conf')


let app = http.createServer ( function(request,response){
    let url = request.url
    if(request.url!=='/favicon.ico'){//清除第二次訪問
        //請求的數據是否存在代理
        for ( var key in conifg){
            if( url.indexOf(key) >-1 ){
                let info = conifg[key].target.split(':')
                console.log('info::'+info)
                let opt = {
                    protocol: info[0]+':',
                    host:    info[1].slice(2),
                    method:  request.method,//這裏是發送的方法
                    path:    conifg[key].target+url,     //這裏是訪問的路徑
                    json: true,
                    headers: request.headers
                }
                console.log(url)
                proxy( opt, response,request )//代理方法
                return;
            }

        }
        //正常的讀取文件和其他資源加載
        fs.readFile( __dirname + ( url==='/' ? '/index.html':url ), function( err, data ){
            if( err ){
                console.log( 'file-err',err )
            }else{
                response.end( data )
            }
        });
    }
} ) 

//代理轉發的方法
function proxy( opt,res ,req){

    var proxyRequest = http.request(opt, function(proxyResponse) { //代理請求獲取的數據再返回給本地res
        proxyResponse.on('data', function(chunk) {
            console.log("proxyRequest res :"+ chunk.toString('utf-8') )
            res.write(chunk, 'binary');
        });
        //當代理請求不再收到新的數據,告知本地res數據寫入完畢。
        proxyResponse.on('end', function() {
            res.end();
        });
        res.writeHead(proxyResponse.statusCode, proxyResponse.headers);
    }); 
    
    //data只有當請求體數據進來時纔會觸發
    //儘管沒有請求體數據進來,data還是要寫,否則不會觸發end事件
    req.on('data', function(chunk) {
        console.log('in request length:', chunk.length);
        proxyRequest.write(chunk, 'binary');
    });

    req.on('end', function() {
        //向proxy發送求情,這裏end方法必須被調用才能發起代理請求
        //所有的客戶端請求都需要通過end來發起
        proxyRequest.end();
    });
    
}


app.listen(8000)
console.log('server is listen on 8000....')

代理配置文件:proxy-conf.js

//代理配置
let config = {
    // 匹配到url包含 pro
    '/pro/':{
        // host替換成這個url
        target: 'http://www.baidu.com',
    },
    // 匹配到url包含 test
    '/test/':{
        // host替換成這個url
        target: 'http://google.com',
    }
}
module.exports = config

這兩個js文件保存到 flutter項目下邊的web文件夾下。

 

寫兩個bat腳本(我只會寫這個。。。)

build_web.bat

@ECHO off
flutter build web

node_proxy_server.bat

@ECHO off
node build/web/server.js

build.bat

@ECHO off
call build_web
call node_proxy_server

這三個文件放在項目根目錄。

每次運行的時候直接使用命令行運行 build 命令。node服務器啓動監聽8000端口。這個時候訪問 localhost:8000就可以打開項目正常進行跨域api請求了。

 

node代理服務器代碼來源:https://github.com/jiangzhenfei/server    感謝【ferry】的代碼分享

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章