webpack的proxy解决开发环境跨越问题

webpack的proxy能够用来代理跨域问题,尝试了很久终于没有踩坑了:html

简单的后端返回数据代码: server.jsnode

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

 

webpack --devServer配置web

  //服务器启动目录;
  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:ajax

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)

        }
    })
};

写一个事件去调用这个函数就能够了:json

这里须要注意了:devServer中的api配置前的 / 不能少,文中标记红色的地方须要一致,否则会报404错误:后端

要么这样简单: devServer.proxy中的api留空(即 url('/') ): $.ajax 中的请求根据业务需求想写啥就写啥....api

 

$.ajax中的 url必需要至少有一个/xxx的结构:否则返回的是本地端口的response;跨域

就是就是说,$.ajax ({ url:"/xxx /xxx / xxx"});至少保留一个/xxx,固然业务上后端的数据确定有一个的..没有也能够配置;服务器

相关文章
相关标签/搜索