如何在JavaScript中将字符串转换为字节数组

时间:2019-07-15 03:39:59

标签: javascript node.js request

我有一个外部系统,该系统接收证书作为请求选项。

可行的解决方案: 证书存储在文件 certificate.crt 中 使用fs包,我编写了以下解决方案:

const options = {
cert: fs.readyFileSync('certificate.crt');
}

request.post(options, (error, response, body) => {
// do something with response
}

使用描述的解决方案,一切正常。

但是我收到了以下要求:

  • 证书文件将存储在环境变量中。 (例如在process.env.CERTIFICATE中)

我尝试了以下解决方案,但没有运气:

const certificateBuffer = Buffer.from(process.env.CERTIFICATE);

const options = {
cert: certificateBuffer
}

request.post(options, (error, response, body) => {
// do something with response
}

也许您会问我,为什么我在解决方案中使用了缓冲区。 我尝试使用console.log可行的解决方案,然后看到readFileSync从文件转换数据并以 ByteArray 发送数据。

我的解决方案收到以下错误:

"Error: error:0906D06C:PEM routines:PEM_read_bio:no start line\n    
at Error (native)\n    
at Object.createSecureContext (_tls_common.js:69:17)\n    
at Object.exports.connect (_tls_wrap.js:1033:48)\n    
at Agent.createConnection (https.js:82:22)\n    
at Agent.createSocket (_http_agent.js:195:26)\n    
at Agent.addRequest (_http_agent.js:157:10)\n    
at new ClientRequest (_http_client.js:160:16)\n    
at Object.exports.request (http.js:31:10)\n    
at Object.exports.request (https.js:202:15)\n    
at Request.start (D:\\home\\site\\wwwroot\\myproject\\node_modules\\request\\request.js:751:32)"

0 个答案:

没有答案