首页 > 解决方案 > 在开发模式下使用 Express 服务器在开发模式下使用 React JS 设置 SSL 客户端身份验证

问题描述

当我使用带有 Node Js https 库的 React Js 在PRODUCTION中使用密钥库身份验证从我的带有自签名 CA 的反应应用程序中获取/发布查询到后端服务器时 - 一切正常(ca:fs.readFileSync('./ssl/ca.crt '))。下面是代码:

var options = {
    hostname: hostname,
    port: port,
    path: pathMethod,
    method: method,
    ca: fs.readFileSync('./ca.crt'),
    checkServerIdentity: function (host, cert) {
        return undefined;
    },
    headers: {
        'Content-Type': APPLICATION_JSON,
    },
    rejectUnauthorized: true,
    agent: false,
    requestCert: true

};

return new Promise(function(resolve, reject) {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var req = https.request(options, function(res) {
        res.setEncoding(ENCODING_UTF8);

        res.on('data', function(result) {

            try {
                const obj = JSON.parse(result);
                resolve({
                    'httpStatus': PAGE_STATUS_200,
                    'token': obj.token,
                    'access': obj.access,
                    'userName': obj.userName,
                    'language': obj.language.toUpperCase(),
                });
            }
            catch(error) {
                console.error(error);
                resolve(resolve({ 'httpStatus': PAGE_STATUS_500 }));
            }

        });

        res.on('end', () => {
            console.log('No more data in response.');
        });
    });

    req.on('error', function(err) {
        console.log(`problem with request: ${err.message}`);
        reject(err);
    });

    if (postData) {
        req.write(postData);
    }

    req.end();
});

但是我遇到了问题,当我在DEVELOPMENT中编写代码时,因为在开发人员中我使用 DEV SERVER 进行热重新部署,提供静态文件和其他可爱的功能,并且在这种模式下,本机 Node Js 模块“fs”不起作用('fs. readFileSync 不是函数'-错误)。我也尝试使用 webpack 的“raw-loader”来上传 CA 证书,并且也习惯了这一行:

node: {
    fs: "empty"
}

但不幸的是,它没有帮助我。我也尝试使用一些代理中间件,例如https://www.npmjs.com/package/express-http-proxy

const app = express()
app.use('/', proxy('https://127.0.0.1:8443', {
    proxyReqOptDecorator: function(proxyReqOpts, originalReq) {
    proxyReqOpts.ca =  [fs.readFileSync('./ca.crt')]
    proxyReqOpts.rejectUnauthorized = true
    proxyReqOpts.agent = false
    proxyReqOpts.requestCert = true
    proxyReqOpts.method = 'POST'
    proxyReqOpts.checkServerIdentity = function (host, cert) {return undefined;}
    return proxyReqOpts;
}

但不幸的是,只有当我直接在浏览器中打印 URL 并按 Enter 时,CA 证书才有效。如果我按下按钮并对后端服务器执行 https 查询 - 它不起作用。

也许有人知道,如何在开发模式下使用 Express 服务器设置 SSL 客户端身份验证,并使用一些中间件或适当的 Webpack 加载器来上传证书或其他技巧?

标签: reactjsexpresssslwebpackca

解决方案


你试过做一个

var fs=require('fs'); 

在 index.js 上,您创建的节点服务器的索引文件


推荐阅读