【问题标题】:Axios api proxy on nuxt doesn't work on server side rendering on now zeit deploynuxt 上的 Axios api 代理现在无法在服务器端渲染上运行 zeit deploy
【发布时间】:2026-01-16 16:05:01
【问题描述】:

Axios NuxtJS config 之后,我在nuxt.config.js 上创建了这样的代理配置:

  proxy: {
    '/api/': {
      target: 'https://myapidomain.com/',
      pathRewrite: { '^/api/': '' },
      changeOrigin: true
    }
  }

此配置在dev 环境下完美运行,无论是服务器端渲染还是客户端渲染。这是我们用来创建 api 包装器api.js 的代码:

export default (context, inject) => {
  inject('api', {
    getPageForSlug: (slugRoute) => {
      return context.$axios.$get(`/api/pageForSlug?routeName=${slugRoute}`)
    },
  })
}

然后从任何 vue 类:

const response = await app.$api.getPageForSlug(params.slug_route)

zeit now 部署调用此代码时会出现唯一的问题。客户端完美运行,但是服务端返回这个错误:

START RequestId: dd92dbad-135f-414b-bc1d-df9faffaa681 Version: $LATEST
2019-08-30T17:46:03.098Z    dd92dbad-135f-414b-bc1d-df9faffaa681    INFO    λ Cold start took: 5265.617811ms
END RequestId: dd92dbad-135f-414b-bc1d-df9faffaa681
REPORT RequestId: dd92dbad-135f-414b-bc1d-df9faffaa681  Duration: 438.53 ms Billed Duration: 500 ms     Memory Size: 3008 MB    Max Memory Used: 92 MB  

N',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     data: undefined },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        autoDestroy: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     domain: null,
     _events:
      [Object: null prototype] { response: [Function], error: [Function] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { protocol: 'http:',
        maxRedirects: 21,
        maxBodyLength: 10485760,
        path: '/api/pageForSlug?routeName=lud_form',
        method: 'GET',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: 'localhost',
        port: '3000',
        nativeProtocols: [Object],
        pathname: '/api/pageForSlug',
        search: '?routeName=lud_form' },
     _redirectCount: 0,
     _redirects: [],
     _requestBodyLength: 0,
     _requestBodyBuffers: [],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Socket],
        connection: [Socket],
        _header:
         'GET /api/pageForSlug?routeName=lud_form HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nx-now-deployment-url: lps-5fxmi58fz.now.sh\r\nx-now-trace: staging-gru1\r\nx-real-ip: 177.45.65.235\r\nx-zeit-co-forwarded-for: 177.45.65.235\r\nupgrade-insecure-requests: 1\r\nx-forwarded-proto: https\r\nx-now-id: 7xllz-1567187175018-d0ce35475a9e\r\naccept-encoding: gzip, deflate\r\nuser-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\r\nx-forwarded-for: 177.45.65.235\r\nx-forwarded-host: lps-danicuki.playax.now.sh\r\ndnt: 1\r\naccept-language: en-US,en;q=0.9\r\nconnection: close\r\nHost: localhost:3000\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/api/pageForSlug?routeName=lud_form',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'http://localhost:3000/api/pageForSlug?routeName=lud_form' },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function] }
END RequestId: 6e355938-32d5-459a-adf7-08fb97101e29
REPORT RequestId: 6e355938-32d5-459a-adf7-08fb97101e29  Duration: 281.53 ms Billed Duration: 300 ms     Memory Size: 3008 MB    Max Memory Used: 117 MB 
RequestId: 6e355938-32d5-459a-adf7-08fb97101e29 Error: Runtime exited with error: exit status 1
Runtime.ExitError 

如何让服务端 API 请求在所有环境下都能正常工作?

【问题讨论】:

    标签: javascript axios nuxt.js vercel


    【解决方案1】:

    这可以在您的now.json Vercel 文件中使用rewrite 来实现。无需破解。

    {
      "version": 2,
      "builds": [
        {
          "src": "nuxt.config.js",
          "use": "@nuxtjs/vercel-builder",
          "config": {}
        }
      ],
      "rewrites": [
        {
          "source": "/api/:match*",
          "destination": "https://myapidomain.com/:match*"
        }
      ]
    }
    

    【讨论】:

      【解决方案2】:

      你准备好迎接终极黑客了吗?

      这实际上是一个常见问题。当调用zeit now 时,服务器实际上并没有得到支撑。因此,您需要自己动手。

      我唯一一次遇到需要这样做的时候,我用 express 来解决它。一个快速而肮脏的解决方案是创建另一个脚本 (proxy.js),并具有如下内容:

      import express from 'express'
      import proxy from 'express-http-proxy'
      const app = express()
      app.use('/', proxy(`https://myapidomain.com`))
      export default app
      

      这只是为您的 API 设置反向代理。

      从那里,在您的 zeit 配置中,找到您的 builds 密钥(如果有),并将其替换为:

      "builds": [
          { "use": "@now/next", "src": "package.json" },
          { "use": "@now/node", "src": "proxy.js" }
      ]
      

      当您使用zeit now 构建时,这将支持并执行proxy.js

      请注意,这确实意味着您需要在proxy.js 中获取主机以匹配“正常”主机。如果您知道配置文件的格式(您应该知道),则可以导入并解析它以获得一个真实来源。

      让我知道这是否有效。

      【讨论】:

      • 我完全按照您的描述做了,但错误仍然相同。这是我的 now.json:{ "version": 2, "builds": [ { "src": "nuxt.config.js", "use": "@nuxtjs/now-builder", "config": {} }, { "use": "@now/node", "src": "proxy.js" } ] }
      • 我遇到了同样的问题,但你的解决方案对我不起作用。我一直在使用代理运行 now.sh 上的 502: BAD_GATEWAY 或在不使用代理的情况下遇到 cors 问题。跨度>
      最近更新 更多