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

如何在Next.js API路由中发起非安全HTTP请求?

解决Next.js生产环境允许HTTP请求的方案

方法1:通过next.config.js配置调整

Next.js默认在生产环境拦截非TLS请求,你可以通过配置文件针对性放开:

module.exports = {
  // 全局临时禁用TLS证书校验(风险较高,谨慎使用)
  env: {
    NODE_TLS_REJECT_UNAUTHORIZED: '0',
  },
  // 针对App Router,可通过重写规则转发请求
  async rewrites() {
    return [
      {
        source: '/api/legacy/:path*',
        destination: 'http://你的旧微服务地址/:path*',
      },
    ];
  },
}

方法2:在API路由中单独跳过验证(Pages Router)

如果用Pages Router的API路由,可在请求代码里单独配置跳过TLS校验:

用Axios的情况

import axios from 'axios';
import https from 'https';

export default async function handler(req, res) {
  const agent = new https.Agent({ rejectUnauthorized: false });
  try {
    const resp = await axios.get('http://你的旧微服务地址/api/xxx', { httpsAgent: agent });
    res.status(200).json(resp.data);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
}

用原生Fetch的情况

import { Agent } from 'https';

export default async function handler(req, res) {
  const agent = new Agent({ rejectUnauthorized: false });
  try {
    const resp = await fetch('http://你的旧微服务地址/api/xxx', { agent });
    const data = await resp.json();
    res.status(200).json(data);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
}

方法3:添加反向代理(推荐,兼顾安全)

如果不想降低Next.js的安全级别,可在中间加一层反向代理(比如Nginx),代理对外提供HTTPS接口,内部转发到旧微服务的HTTP地址:

server {
  listen 443 ssl;
  server_name proxy.your-domain.com;

  ssl_certificate /path/to/your-cert.pem;
  ssl_certificate_key /path/to/your-key.pem;

  location / {
    proxy_pass http://你的旧微服务IP:端口;
    proxy_set_header Host $host;
  }
}

之后Next.js只需请求https://proxy.your-domain.com即可,既符合安全要求,又能对接旧服务。

注意事项

  • 全局设置NODE_TLS_REJECT_UNAUTHORIZED=0会禁用所有TLS证书校验,风险较高,优先用单独配置Agent的方式。
  • 反向代理是最安全的折中方案,避免直接在业务代码中降低安全标准。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:57:19