Webpack-dev-server 通过代理无法将请求发送到外部域

6
我将尝试使用webpack-dev-server代理配置将API请求发送到外部域名,但似乎无法使其正常工作。
这是我的配置:
var path = require('path')

module.exports = {
    entry: './client/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'public/assets'),
        publicPath: 'assets'
    },
    devServer: {
        contentBase: 'public',
        proxy:{
            '/api/v1*': {
                target: 'http://laravelandwebpack.demo/',
                secure: false
            }
        }
    }
}

所以,每当我的应用程序使用uri /api/v1... 发出请求时,它应该将该请求发送到http://laravelandwebpack.demo
在我的Vue应用程序中,我正在使用vue-resource来发出请求,并将所有请求默认为所需的uri前缀:
var Vue = require('vue')
Vue.use(require('vue-resource'))

new Vue({
    el: 'body',
    http: {
        root: '/api/v1', // prefix all requests with this
        headers:{
            test: 'testheader'
        }
    },
    ready: function (){
        this.$http({
            url: 'tasks',
            method: 'GET'
        }).then(function (response){
            console.log(response);
        }, function (response){
            console.error(response);
        })
    }
})

URL已经正确构建,但它们仍然指向webpack-dev-server上的localhost:8080。

Errant http request

我阅读了webpack-dev-server的文档,但无法确定我的设置是否正确。有任何想法吗?

1
URL正确指向localhost:8080,因为那是您的开发服务器,只有请求到达那里后,开发服务器才会代理它(即将其发送到)您提供的外部URL。开发工具永远不会注意到代理。您的请求会发生什么?promise.catch()是否记录了错误?这是什么?(您不会碰巧使用vue-cli的webpack模板吗?) - Linus Borg
2个回答

2

@Linus Borg是正确的。

URL已正确构建,但仍指向webpack-dev-server的localhost:8080:

这并不重要。

在我的情况下,我想获得http://m.kugou.com/?json=true。我正在使用@Vue/cli ^3.0.0-beta.15,也许您需要根据情况修改代码。

因此,这是我所做的:

App.vue

  axios.get('/proxy_api/?json=true').then(data => {
    console.log('data', data)
  })

vue.config.js

module.exports = {
  devServer: {
    proxy: {
      // proxy all requests whose path starting with /proxy_api to http://m.kugou.com/proxy_api then remove '/proxy_api' string
      '/proxy_api': {
        target: 'http://m.kugou.com',
        pathRewrite: {
          '^/proxy_api': '/'
        }
      }
    }
    //or just change the origin to http://m.kugou.com
    // proxy: 'http://m.kugou.com'
  }
}

我使用/proxy_api/?json=true,然后通过targetpathRewrite将其更新为http://m.kugou.com/?json=true

'/proxy_api'用于区分URL是否应该被代理。

为什么要使用/proxy_api? 方便区分。

我从http://m.kugou.com/?json=true获取数据,而开发工具中的URL为http://localhost:8080/proxy_api/?json=true

明白了吗?这并不重要。


1
我发现了一个解决该问题的变通方法。在我的情况下,我需要将任何 /api/* 路径的请求代理到后端,因此我绕过了不以 api 开头的任何请求。
示例: proxy: { '*': { target: 'http://localhost:8081', secure: false, rewrite: function(req) { console.log('改写'); req.url = req.url.replace(/^\/api/, ''); }, bypass: function(req, res, proxyOptions) { if (req.url.indexOf('api') !== 0) { console.log('跳过浏览器请求的代理。'); return '/index.html'; }else{ return false; } } } }

你把这个对象放在哪个配置文件中了? - partizanos
在 webpack 配置文件中的 devServer 中, - Sakhi Mansoor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接