【问题标题】:Unable to verify the first certificate Next.js无法验证第一个证书 Next.js
【发布时间】:2021-03-26 00:38:02
【问题描述】:

我正在尝试构建一个新应用程序。

它访问一个 API 以通过 HTTPS 获取一些数据。

Status2.getInitialProps = async () => {
    console.info('ENTERRRRRRRR')
    const res = await fetch('https://test.com/api/v1/messages', {
            method: 'get',
            headers: {
                'Authorization': 'Bearer ffhdfksdfsfsflksfgjflkjW50aXNocjEiLCJpYXQiOjE2MDc1ODIzODQsImF1ZCI6InJlY3J1aXRpbmdhcHAtMTAwMC5kZXZlbG9wLnVtYW50aXMuY29tIiwiaXNzIjoicmVjcnVpdGluZ2FwcC0xMDAwLmRldmVsb3AudW1hbnRpcy5jb20ifQ.0jqPutPOM5UC_HNbTxRiKZd7xVc3T5Mn3SjD8NfpEGE',
                'Accept': 'application/vnd.api+json'
            }
        }
    )
}

当浏览器尝试访问此 API 时,它会给我以下错误:

Server Error
FetchError: request to https://test.com/api/v1/messages failed, reason: unable to verify the first certificate

This error happened while generating the page. Any console logs will be displayed in the terminal window.
C

为了解决这个问题,我关注了this,但是在尝试时,它又给了我一个错误:

'NODE_TLS_REJECT_UNAUTHORIZED' is not recognized as an internal or external command,
operable program or batch file.

【问题讨论】:

    标签: npm next.js


    【解决方案1】:

    NODE_TLS_REJECT_UNAUTHORIZED 解决方案不可行,因为它违背了在前端和 API 之间建立可信连接的主要目的。我们最近在使用 NextJS 作为前端、ExpressJS 作为后端、Nginx 作为 Web 服务器时遇到了这个错误消息。

    如果您或您的团队正在实施 API,我建议您查看您的网络服务器配置以及您如何处理证书的路径,因为问题可能与中间证书的错误配置有关。像这样将证书+中间证书结合起来对我们来说是诀窍:

    # make command
    cat {certificate file} {intermediate certificate file} > {new file}
     
    # config file /etc/nginx/conf.d/xxx.conf
    ssl_certificate {new file};
    

    【讨论】:

      【解决方案2】:

      如果您的项目中还没有 next.config.js 文件,请创建一个文件并将以下内容添加到您的 webpack 配置中:

      const webpack = require("webpack");
      
      module.exports = {
        webpack: (config) => {
          config.node = {
            fs: "empty",
          };
      
          process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
          const env = Object.keys(process.env).reduce((acc, curr) => {
            acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
            return acc;
          }, {});
      
          config.plugins.push(new webpack.DefinePlugin(env));
      
          return config;
        },
      }; 
      

      不要在生产中这样使用它。它只能在开发环境中使用。

      【讨论】:

      • 不利于生产
      • 那么发布一个不可行的解决方案有什么意义呢?
      猜你喜欢
      • 2021-10-20
      • 2021-01-02
      • 2020-02-17
      • 1970-01-01
      • 2018-08-29
      • 2020-03-29
      • 2021-06-15
      • 1970-01-01
      • 2017-09-07
      相关资源
      最近更新 更多