Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proxy: webpack devServer 和 axios 拦截 #16

Open
NoName4Me opened this issue Jul 16, 2018 · 0 comments
Open

proxy: webpack devServer 和 axios 拦截 #16

NoName4Me opened this issue Jul 16, 2018 · 0 comments
Labels

Comments

@NoName4Me
Copy link
Owner

其实网上一大堆用这个做跨域处理的,这应该只是一个小功能。

webpack devServer

  • devServer#proxy 中配置

注意: 假设 devServer 运行在 localhost:3001 下,webServer 只能代理 localhost:3001/xxx 这种请求,无法拦截外部 API,比如 http://external.com/xxx,但是它可以把内部请求代理到外部。

devServer: {
  proxy: {
    '/api': {
      target: 'https://for.example.com',
      pathRewrite: function(path, req) {
        return path;
      }
    }
  }
}
// 如果使用 vue 官方提供的模板的话,在 proxyTable 里面
  • devServer#before 中配置
devServer: {
  before: (app) => {
    // for some special url or *(filter `query` or other things except `url`)
    app.get('/api', (req, res, next) => {
      // do something with `req` `res` `next`
      res.json({ msg: 'hi~' });
      // next();
    });
  }
}
// 如果使用 vue 官方模板的话,在 proxyTable 里面

axios 拦截

instance.interceptors.request.use(function (config) {
  // proxy triggered
  // you can modify the `config.url` to your target proxy server
  config.method = 'post';
  
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

参考

  1. http-proxy-middleware: https://github.com/chimurai/http-proxy-middleware
  2. axios: https://github.com/axios/axios
@NoName4Me NoName4Me added the label Jul 16, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant