12.webpack的跨域配置

跨域

前端请求的转发过程

假设后端请求是3000端口,webpack是8080端口

  1. 第一步:先发送到8080这个webpack-dev-server的服务
  2. 第二部:再转发给后端的3000端口

webpack配置

//js请求
let xhr = new XMLHttpRequest();
xhr.open('GET','/api/user',true);
xhr.onload = function(){
	console.log(xhr.response);
}

xhr.send();


//webpack.config.js
module.exports = {
	devServer:{
		proxy:{
			'/api':'http://localhost:3000'//配置了一个代理
		}
	}
}

这样就能转发到后端的3000端口了

问题来了

如果这样的话,我没写一个请求,都要写一个proxy,比较麻烦。有没有简单的方法

简单方法如下:

proxy的配置优化

  1. 通过重写的方式,把请求代理到后端服务器上
//js
let xhr = new XMLHttpRequest();
xhr.open('GET','/api/user',true);
xhr.onload = function(){
	console.log(xhr.response);
}

xhr.send();

//webpack.config.js
module.exports = {
	devServer:{
		'/api':{
			target:'http://localhost:3000',
			pathRewrite:{'/api':''}
		}
	}
}

//后端就不需要使用/api/user了,直接使用/user,因为前段已经重写了
app.get('/user',(req,res) => {
	res.json({name:'yuhua'})
})

如果前端只想单纯来mock数据

  1. 无需后端,只需前端,使用devServer中的before函数。当然,因为是本地模拟,无需后端,自然也就不存在跨域问题了
//js中
let xhr = new XMLHttpRequest();
xhr.open('GET','/api/user',true);
xhr.onload = function(){
	console.log(xhr.response);
}

xhr.send();
//webpack.config.js
devServer:{
	before(app){
		app.get('/api/user',(req,res) => {
			res.json({name:'yuhua-before'})
		})
	}
}

后端来启动前端(比较特别)

  1. 前端js
let xhr = new XMLHttpRequest();
xhr.open('GET','/user',true);
xhr.onload = function(){
	console.log(xhr.response);
}

xhr.send();
  1. 后端server.js(express)
    d
    1. 安装中间件webpack-dev-middleware
        npm i webpack-dev-middleware -D
    
    1. 需要引入webpack
    2. 引入中间件
    3. 引入webpack配置文件
    4. 获取webpack对配置文件的处理结果
    5. 使用中间件,传入配置文件的处理结果
let express = require('express');

let app = express();

let webpack = require('webpack');
//中间件 npm i webpack-dev-middleware -D
//引入中间件
let middle = require('webpack-dev-middleware');
//引入webpack配置文件
let config = require('./webpack.config.js');
//获取结果
let compiler = webpack(config);
//使用中间件,传入结果
app.use(middle(compiler));



app.get('/user',(req,res) => {
	res.json({name:'yuhua'})
})

app.listen(3000);

  1. 启动后端,即node server.js,相当于执行了后端的node sercer.js以及前端的npm run dev
  2. 浏览器访问后端的端口,即localhost:3000,能够正常请求
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值