说说webpack proxy的工作原理?
# 是什么
webpack-dev-server: 开发阶段使用的中间服务器
# 怎么用
// ./webpack.config.js
const path = require('path')
module.exports = {
// ...
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
proxy: {
'/api': {
target: 'https://api.github.com'
}
}
// ...
}
}
# 原理
带api前缀请求 ---> 中间服务器 ---> 目的服务器
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();
app.use('/api', proxy({target: 'http://www.example.org', changeOrigin: true}));
app.listen(3000);
// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
# FAQ
跨域是浏览器的同源策略原因, 服务器之间通信不存在跨域问题
上次更新: 2021/12/19, 18:05:42