如何在 Nuxt 中使用 webpack 开发代理 [英] How to use webpack dev proxy with Nuxt

查看:105
本文介绍了如何在 Nuxt 中使用 webpack 开发代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Nuxt 开发通用 JS 应用程序,我正在尝试配置 webpack 的开发代理 这样,仅在开发中,请求/api 被代理到 http://127.0.0.1:500/api 那里他们将到达 Python REST API.按照 Nuxt 文档,我在 nuxt.config 中扩展了 webpack 配置.js 像这样:

Using Nuxt to develop a universal JS app, I'm attempting to configure webpack's dev proxy so that, in development only, requests to /api get proxied to http://127.0.0.1:500/api where they'll reach a Python REST API. Following the Nuxt docs, I've extended the webpack config in nuxt.config.js like so:

build: {
  extend (config, { isDev }) {
    // Proxy /api to Python only in dev
    if (isDev) {
      const devServer = {
        proxy: {
          '/api': 'http://127.0.0.1:5000'
        }
      }
      config.devServer = devServer;
    }
  }
}

如果我记录配置,我会看到正在应用更改:

If I log the config, I see that change being applied:

...
devServer: { proxy: { '/api': 'http://127.0.0.1:5000' } } }
...

然而,当我访问 http://127.0.0.1:8080/api/things,我的 Nuxt 应用程序返回(它在 dev 中的端口 8080 上运行),表明 webpack dev 代理没有捕获 /api 路径并执行代理.只是为了确认代理 destination 正在工作,如果我访问 http://127.0.0.1:5000/api/things,我得到了预期的 API 响应.为什么,当我扩展 Nuxt webpack 配置以启用 webpack 开发代理时,代理不起作用?

Yet, when I visit http://127.0.0.1:8080/api/things, my Nuxt app is returned (it runs on port 8080 in dev), indicating that the webpack dev proxy is not catching the /api path and performing the proxying. Just to confirm that the proxy destination is working, if I visit http://127.0.0.1:5000/api/things, I get the expected API response. Why, when I've extended the Nuxt webpack config to enable the webpack dev proxy, does the proxy not function?

但是,我在 @nuxt/proxy 模块上取得了成功,但至关重要的是,我找不到一种方法让它只影响开发而不影响生产.nuxt.config.js 的那部分看起来像这样:

I have, however, had success with the @nuxt/proxy module, but critically, I could not find a way to make it only affect development and not production. That portion of nuxt.config.js looked like this:

axios: {
  proxy: true
},
proxy: {
  '/api': 'http://127.0.0.1:5000'
},

我很高兴使用@nuxt/proxy 模块而不是(在上面?)webpack 开发代理,如果它只能在开发中工作.

I'm happy to use the @nuxt/proxy module instead of (on top of?) the webpack dev proxy if it can be made to work in development only.

推荐答案

呃,我说错了.

Nuxt 需要代理,即使在生产中也是如此.当我的初始请求被处理并且应用程序在服务器端呈现时,任何 API 请求都需要被代理,因为 Node 服务器正在执行调用,而不是浏览器,因此这些 API 请求甚至不会像 nginx 那样命中我的生产路由器或 HAProxy(通常将 //api 路由到适当的服务).

Nuxt needs to proxy, even in production. When my initial request is processed and the app is server-side-rendered, any API requests need to be proxied because the Node server is doing the calling, not a browser, so those API requests won't even hit my production router like nginx or HAProxy (which typically does my routing for / and /api to the appropriate services).

这篇关于如何在 Nuxt 中使用 webpack 开发代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆