分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

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

发布时间:2023-09-06 02:11责任编辑:彭小芳关键词:webpack

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,当然业务上后端的数据肯定有一个的..没有也可以配置;

 

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

原文地址:https://www.cnblogs.com/liuliu-hai/p/9513775.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved