nodejs支援建立https服務,如果在
localhost
下需要自己制作免費的https證書
import {sslOption} from './src/configs/https'
import { IncomingMessage, ServerResponse, RequestListener, Server } from 'http';
import {createServer} from 'https';
//證書
const sslOption = {
key: readFileSync('src/configs/localhost.key'), // 私鑰(必須使用相對路徑,不允許`~`代替)
cert: readFileSync('src/configs/localhost.crt') // 證書
}
// 監聽
const listner: RequestListener = (req: IncomingMessage, res: ServerResponse) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({name:'你好'}))
}
// 建立server對象
const server: Server = createServer({...sslOption}, listner);
// 啟動
server.listen(PORT, () => {
console.log(`start server success, port=${PORT}`)
});
參考文獻
- [如何建立
的https證書]https://letsencrypt.org/zh-cn/docs/certificates-for-localhost/)localhost
- 2.使用原生nodejs建立https服務-2步走
- 3.開啟https服務後,chrome浏覽器通路
提示不安全警告https://localhost
,處理方案NET::ERR_CERT_INVALID