11

~ 我使用的是 Node 10.9.0 和 npm 6.2.0 ~

http我正在运行以下应用程序,它允许我一遍又一遍地向同一个站点发出请求https

var fetch = require('node-fetch')
const express = require('express')
const app = express()

//-- HTTP --
app.get('/test-no-ssl', function(req, res){
  fetch('http://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(users => {
    res.send(users)
  }).catch(function(error) {
    res.send(error)
  })
})

//-- HTTPS --
app.get('/test-ssl', function(req, res){
  fetch('https://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(users => {
    res.send(users)
  }).catch(function(error) {
    res.send(error)
  })
})

app.listen(3003, () => 
  console.log('Listening on port 3003...')
)

这两种方法都可以在我的本地机器上正常工作,并返回 Typicode 提供的 JSON 响应。但是当我在我的网络主机 ( FastComet ) 上将它们部署为 Node 应用程序时,我得到以下结果:

HTTP /test-no-ssl - 按预期返回 JSON

HTTPS /test-ssl - 返回以下错误:

{ 
  "message" : "request to https://jsonplaceholder.typicode.com/users failed, reason: unable to get local issuer certificate",
  "type" : "system",
  "errno" : "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
  "code" : "UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
}

我搜索了这个错误并尝试了一些常见的修复方法,但没有任何帮助。

这些不起作用:

npm config set registry http://registry.npmjs.org/

npm set strict-ssl=false

有没有其他人在共享托管服务提供商(支持 Node)上遇到这个问题并且能够让它工作?也许甚至是使用 FastComet 的人?主持人的后勤人员似乎也不知道该怎么办,所以我很茫然。

4

2 回答 2

26

尝试使用以下内容:

process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0
于 2018-12-11T05:15:49.447 回答
6

托管可能与证书颁发机构列表存在一些问题......作为一种解决方法,您可以尝试忽略证书有效性。

const fetch = require('node-fetch')
const https = require('https')
const express = require('express')
const app = express()

const agent = new https.Agent({
  rejectUnauthorized: false
})

//-- HTTP --
app.get('/test-no-ssl', function(req, res){
  fetch('http://jsonplaceholder.typicode.com/users')
    .then(res => res.json())
    .then(users => {
      res.send(users)
    }).catch(function(error) {
    res.send(error)
  })
})

//-- HTTPS --
app.get('/test-ssl', function(req, res){
  fetch('https://jsonplaceholder.typicode.com/users', { agent })
    .then(res => res.json())
    .then(users => {
      res.send(users)
    }).catch(function(error) {
    res.send(error)
  })
})

app.listen(3003, () =>
  console.log('Listening on port 3003...')
)

注意:这有安全隐患,使 https 与 http 一样不安全。

于 2018-08-24T11:47:11.210 回答