proxy: {
 '/': {
  target: 'https://api.example.com',
  secure: false,
  bypass: function(req, res, proxyOptions) {
   if (req.headers.accept.indexOf('html') !== -1) {
    console.log('Skipping proxy for browser request.');
    return '/index.html';
   }
  }
 }
}
如上配置,可以监听https://api.example.com域下的/开头的请求(等效于所有请求),然后判断请求头中accept字段是否包含html,若包含,则代理请求至/index.html,随后将返回index.html文档至浏览器。
解决问题
综合以上方案,因为在webpack配置中修改了output.publicPath为/assets/,所以博主采用webpack-dev-server Proxy代理方式解决了问题:
const PUBLICPATH = '/assets/'
...
proxy: {
 '/': {
  bypass: function (req, res, proxyOptions) {
   console.log('Skipping proxy for browser request.')
   return `${PUBLICPATH}/index.html`
  }
 }
}
监听所有前端路由,然后直接返回${PUBLICPATH}/index.html,PUBLICPATH就是设置的output.publicPath值。
另外,博主总是习惯性的声明,虽然不设置该属性也能满足预期访问效果:
historyApiFallback: true
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
