【问题标题】:Nuxt static generated page and axios postNuxt 静态生成页面和 axios post
【发布时间】:2020-07-29 17:31:21
【问题描述】:

我有一个 Nuxt 项目。生成静态页面时一切正常。 但是,我需要向其他服务器发送 POST 请求。

我尝试在 nuxt.config.js 中使用代理和直接查询,但最终部署到 ngnix 后,没有任何效果。

请帮忙。


更新。重现步骤。

  • 创建包含 axios 和代理的 Nuxt 应用
  • 为其他网络服务配置您的代理:

proxy: { '/api': { target: 'http://example.com:9000', pathRewrite: { '^/api': '/', }, }, changeOrigin: true, },

  • 在代码中的某处调用此服务:

    const result = await this.$axios.post('/api/email/subscribe', {email: email})

  • 运行“yarn dev”并测试服务。它在本地正常工作。

  • 运行“nuxt generate”并部署静态代码托管服务,例如hosting.com
  • 运行调用上述服务的页面。

因此,它不是对hosting.com/api/email/subscribe 进行POST 调用,而是调用localhost:3000/api/email/subscribe。

【问题讨论】:

  • 请详细说明“没有任何作用”。您的代码试图做什么?您是否在浏览器控制台中看到任何错误消息?

标签: vue.js axios nuxt.js


【解决方案1】:

一定要在你的项目@nuxt/axios和@nuxtjs/proxy中安装nuxt版本的axios和proxy

之后在你的 nuxt.config.js 中添加 axios 作为模块加上 axios 和代理的这个选项:

  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    //more modules if you need
  ],
  /*
   ** Axios module configuration
   */
  axios: {
    proxy: true,
    // See https://github.com/nuxt-community/axios-module#options
  },

  proxy: {
    '/api/': {
      target: process.env.AXIOS_SERVER, // I use .env files for the variables
      pathRewrite: { '^/api/': '' }, //this should be your bug
    },
  },

现在你可以像这样在代码的任何部分使用 axios

const result = await this.$axios.post('/api/email/subscribe', {email: email})

它将在内部解析为 AXIOS_SERVER/email/subscribe 而不会导致 cors 问题。

EXTRA:使用多个 .env 文件在本地测试环境

您可以为 dev 配置 .env 和为生产配置 .env.prod,之后在本地您可以使用 yarn build && yarn start 在您的生产环境中测试您的应用程序。你只需要在你的 nuxt.config.js 文件的顶部添加这个

const fs = require('fs')
const path = require('path')

if (process.env.NODE_ENV === 'production' && fs.existsSync('.env.prod')) {
  require('dotenv').config({ path: path.join(__dirname, `.env.prod`) })
} else {
  require('dotenv').config()
}

【讨论】:

  • 谢谢,我看到你使用了 'yarn build' 和 'yarn start' 你试过 'yarn generate' 吗?简而言之,问题只出现在纱线生成中!
  • 你有两个问题, localhost:3000 意味着你在 axios 或代理中配置了服务器名称。我的代码解决了这个问题。另一个问题是静态与通用的概念。使用 generate 你有一个静态版本的网站,它是前端。服务器端没了。那么代理是服务器端代码它不是在静态模式下运行很正常
  • 您的站点调用 localhost:3000 的其他可能原因是,如果您使用 CI 检查变量是否已收费,则在生成过程中无法处理 .env。
【解决方案2】:

definition on the Nuxt docs pagenuxt generate 所做的是:构建应用程序并将每个路由生成为 HTML 文件(用于静态托管)。

因此,在这里使用proxy 是不可能的。请注意,您的路径甚至没有被重写。

您要查找的结果可能不是hosting.com/api/email/subscribe(即/api),而是hosting.com/email/subscribe。

尽管如此,如果您使用 nginx,那么我认为您不应该使用 Nuxt 的 proxy 选项。 Nginx 就是为此而构建的,因此将您的 API 调用指向那里,并在 nginx 配置文件中声明它应该进一步指向的位置。

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 1970-01-01
    • 2012-07-08
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多