You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NuxtJS 2部署Vercel后serverMiddleware接口请求遭客户端拦截求助

解决NuxtJS 2部署Vercel后serverMiddleware接口请求指向localhost的问题

问题根源

  1. Nuxt的serverMiddleware依赖自身服务器运行,但Vercel部署Nuxt2采用Serverless函数模型,原生不支持该配置,导致接口无法正常映射。
  2. axios的baseURL配置可能在生产环境错误指向localhost:3000,引发客户端请求地址异常,进而触发浏览器插件拦截(ERR_BLOCKED_BY_CLIENT)。

修复步骤

1. 修正axios基础地址配置

打开nuxt.config.js,确保axios模块的baseURL适配生产环境:

export default {
  // ...其他配置
  axios: {
    // 生产环境留空,自动使用当前域名作为基础地址;开发环境指向本地
    baseURL: process.env.NODE_ENV === 'production' ? '' : 'http://localhost:3000'
  }
}

若之前手动设置生产环境baseURL为localhost,直接删除该配置即可。

2. 适配Vercel Serverless Functions

Vercel通过根目录的api文件夹识别Serverless函数,需替换原Nuxt serverMiddleware配置:

  • 移除nuxt.config.js中的serverMiddleware配置:
    删除以下配置行:
    serverMiddleware: [{ path: '/api', handler: '~/api/newsletter.ts' }],
    
  • 迁移接口逻辑到Vercel函数:
    在项目根目录创建api文件夹,新建subscribe.ts文件,将原~/api/newsletter.ts中的订阅逻辑迁移过来,调整为Vercel函数格式:
    import { VercelRequest, VercelResponse } from '@vercel/node'
    
    export default async function handler(req: VercelRequest, res: VercelResponse) {
      // 仅处理POST请求
      if (req.method !== 'POST') {
        res.setHeader('Allow', ['POST'])
        return res.status(405).json({ title: 'Method Not Allowed' })
      }
    
      try {
        const { email } = req.body
        // 写入你的订阅业务逻辑(如调用邮件服务、数据库操作等)
        
        return res.status(200).json({ message: '订阅成功' })
      } catch (error) {
        return res.status(500).json({ title: '订阅失败,请稍后重试' })
      }
    }
    
  • 安装依赖:
    执行命令安装Vercel Node函数的类型依赖:
    npm install @vercel/node --save-dev
    

3. 重新部署测试

将代码提交到Git仓库,触发Vercel重新部署。部署完成后调用/api/subscribe接口,此时请求会指向Vercel域名而非localhost,浏览器插件也不会再拦截正常的域名请求。


内容的提问来源于stack exchange,提问作者Vivallo04

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:32:35