背景

有的时候,后端接口还没开发完,前端无法调用获取数据进行开发。这时候就可以在 webpack 中模拟数据返回。
这种方式同样可以解决跨域问题。

webpack 配置

  1. //...
  2. module.exports = {
  3. //...
  4. devServer: {
  5. port: 3000,
  6. open: true,
  7. compress: true,
  8. static: './dist',
  9. onBeforeSetupMiddleware(devServer){
  10. devServer.app.get('/api/user',(req, res)=>{
  11. res.json({name: 'before'});
  12. })
  13. },
  14. }
  15. //...
  16. }
  17. //...

onBeforeSetupMiddleware 方法中的 devServer 中的 app 就是我们通过 express 创造的 app,我们可以直接在这个里面设置路由,相当于创造了一个 3000 端口的服务。

例子

还是前几章的例子

  1. const xhr = new XMLHttpRequest();
  2. xhr.open('get', '/api/user', true);
  3. xhr.onload = () => {
  4. console.log(xhr.response);
  5. };
  6. xhr.send();
  7. // http-proxy
  8. // webpack中集成了 http-proxy-middleware

yarn dev 启动后,再看页面请求
image.png
image.png
请求成功并且返回 before。