vue设置跨域代理

95 阅读1分钟

pathRewrite 的理解

比如我们请求的 /vue/auth,我们期望的最终请求是 localhost:8081/auth/

如果不写pathRewrite ,真正请求的是 localhost:8081/vue/auth/

如果写了pathRewrite,比如 '^/vue': '/',真正请求的是localhost:8081/auth/

比如'^/vue': '/java' ,真正请求的是 localhost:8081/java/auth/

这个应该是3以上的 onProxyReq 解决post请求发不出的问题

module.exports = {
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    before: require('./mock/mock-server.js'),
    proxy: {
      '/vue': { // /vue代理target
        target: 'http://localhost:8081/', // 后端接口的根目录
        // secure: true,                       // 如果是 https ,需要开启这个选项
        changeOrigin: true, // 是否跨域
        pathRewrite: { // 是否重写路径,看代理前端路径是否与后端路径一致
          // '^/vue': '/java'---> localhost:8080/vue/auth/ 通过代理服务器访问 localhost:8081/java/auth/
          '^/vue': '/'
        },
        onProxyReq: function(proxyReq, req, res, options) {
          if (req.body) {
            const bodyData = JSON.stringify(req.body)
            // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
            proxyReq.setHeader('Content-Type', 'application/json')
            proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
            // stream the content
            proxyReq.write(bodyData)
          }
        }
      }
    }
  },

这个应该是2以上 onProxyReq 解决post请求发不出的问题

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    /*todo 设置代理 这里设置之后如果不生效 尝试重新运行*/
    proxyTable: {
      "/vue": {                                 // /vue代理target
        target: 'http://localhost:8080/',      // 后端接口的根目录
        // secure: true,                       // 如果是 https ,需要开启这个选项
        changeOrigin: true,                    // 是否跨域
        pathRewrite: {                         // 是否重写路径,看代理前端路径是否与后端路径一致
          // '^/vue': '/java'---> localhost:8080/vue/auth/ 通过代理服务器访问 localhost:8081/java/auth/
          '^/vue': '/'
        },
       onProxyReq: function(proxyReq, req, res, options) {
          if (req.body) {
            const bodyData = JSON.stringify(req.body)
            // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
            proxyReq.setHeader('Content-Type', 'application/json')
            proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
            // stream the content
            proxyReq.write(bodyData)
          }
        }
      }
    },