webpack的proxy解決開發環境跨越問題


webpack的proxy可以用來代理跨域問題,嘗試了好久終於沒有踩坑了:

簡單的后端返回數據代碼: server.js

var http = require('http');
var url = require('url');
var createServer = http.createServer(onRequest);

var data_list=[
    {name:"liuhf1",age:18,is_show:true},
    {name:"海龍s",age:10,is_show:true},
    {name:"丁丁當當",age:18,is_show:true},
    {name:"沉魚落雁",age:34,is_show:true},
    {name:"小喬流水",age:19,is_show:true},
    {name:"namsss",age:12,is_show:false},
    {name:"liuhf1",age:18,is_show:true},
]
 
function onRequest(request, response) {

    response.writeHead(200, {
        // 'Content-Type': 'text/plain',
        'Content-Type': 'application/json',
        // 'Access-Control-Allow-Origin': '*',         注釋掉這一行; 這個本來就允許跨域的:
        'content-type':'text/html;charset="utf-8'
    });

    var str = url.parse(request.url, true).query;
    console.log(str);

    if(str.test=='ajax'){

        response.write(JSON.stringify(data_list));
        response.end();
    }
    if(str.test=='ajax1'){
        var obj={};
        obj["query"]=str;
        obj["pathname"]=url.parse(request.url, true).pathname;
        
        console.log(obj);
        var obj1=JSON.stringify(obj);
        
        response.write(obj1);

        response.end();
    }
}
createServer.listen(8087);

console.log('Server running  at http://127.0.0.1:8087/');

本地安裝node后,cmd到文件的目錄,運行一下代碼: node server.js(這個文件在哪個目錄並不重要.)

 

webpack --devServer配置

  //服務器啟動目錄;
  devServer: {
    contentBase: './dist',
    hot: true,
    // host:'1ocalhost',
    port: 8586,
    // compress:true,

    //解決跨域
    proxy: {
      '/api': {
        target: 'http://localhost:8087',
        pathRewrite: { '^/api': '' },
        changeOrigin: true,
        secure: false, // 接受 運行在 https 上的服務
      }
    }
  },

客戶端的js:

function ajax() {
    $.ajax({
        url: '/api',
        dataType: 'json',
        // contentType:"application/json",
        type: 'get',
        data: {
            test: 'ajax',
        },
        success: function (res) {
            var data=res;
            console.log(data);
            var str="";

            // $("#list").html(template("list_template",data));
            data.forEach(function(item,key){
                str+="<li class="+item.is_show+">"+item.name+"</li>"
            });
            $("#list").html(str)

        }
    })
};

寫一個事件去調用這個函數就可以了:

這里需要注意了:devServer中的api配置前的 / 不能少,文中標記紅色的地方需要一致,不然會報404錯誤:

要么這樣簡單: devServer.proxy中的api留空(即 url('/') ): $.ajax 中的請求根據業務需求想寫啥就寫啥....

 

$.ajax中的 url必須要至少有一個/xxx的結構:不然返回的是本地端口的response;

就是就是說,$.ajax ({ url:"/xxx /xxx / xxx"});至少保留一個/xxx,當然業務上后端的數據肯定有一個的..沒有也可以配置;

 

 

 


免責聲明!

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



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