背景
有的时候,后端接口还没开发完,前端无法调用获取数据进行开发。这时候就可以在 webpack 中模拟数据返回。
这种方式同样可以解决跨域问题。
webpack 配置
//...module.exports = {//...devServer: {port: 3000,open: true,compress: true,static: './dist',onBeforeSetupMiddleware(devServer){devServer.app.get('/api/user',(req, res)=>{res.json({name: 'before'});})},}//...}//...
onBeforeSetupMiddleware 方法中的 devServer 中的 app 就是我们通过 express 创造的 app,我们可以直接在这个里面设置路由,相当于创造了一个 3000 端口的服务。
例子
还是前几章的例子
const xhr = new XMLHttpRequest();xhr.open('get', '/api/user', true);xhr.onload = () => {console.log(xhr.response);};xhr.send();// http-proxy// webpack中集成了 http-proxy-middleware
yarn dev 启动后,再看页面请求

请求成功并且返回 before。
