美文网首页
webpack配置proxy转发404

webpack配置proxy转发404

作者: 钱英俊真英俊 | 来源:发表于2019-09-26 15:17 被阅读0次

    webpack开发环境处理跨域的方法就是配置devServer的proxy,在服务器接口的nginx根据域名有多个分发的时候,会报404

    • 通用配置: cinfig-index.js(基于vue-cli 2.x)
    dev: {
        proxyTable: {
          '/dev': {
            target: "http://xxx.xxxxxx.xx", // 转发到的服务器的域名/IP
            pathRewrite: {
              "^/dev": ""  // 重写path
            },
          }
        },
    
    原理:

    webpack使用的是http-proxy-middleware的包,找到配置


    进而去看http-proxy的源码,打印请求配置:

    看出:host是请求的地址,但在headers里,hosth还是localhost:8082,此时请求是报404的,所以去找服务端的错误日志


    nginx从请求头里找到的host为localhost,和转发的配置规则不一样,就走到默认的路径里去里,自然找不到资源

    解决办法: changeOrigin: true

    http-proxy的源码里关于请求头的配置:

    该项是需要配置的:config-index.js

    dev: {
        proxyTable: {
          '/dev': {
            target: "http://xxx.xxxxxx.xx", // 转发到的服务器的域名/IP
            pathRewrite: {
              "^/dev": ""  // 重写path
            },
            changeOrigin: true  // 配置请求头
          } 
        },
    

    再来看请求头信息:



    就改为配置的域名了。
    这时候就请求通过了。

    小结

    其实还是http协议的内容,没有出现bug就会忽视细节。多巩固原理吧。

    相关文章

      网友评论

          本文标题:webpack配置proxy转发404

          本文链接:https://www.haomeiwen.com/subject/exacyctx.html