如何为以下设置安装SSL(React Frontend+Nodejs Backend+Custom Domain Her



关于我的设置的一般信息

目前,我正在使用react和nodejs API构建一个web应用程序,为该web应用程序提供数据。这两个应用程序都托管在heroku.com上,彼此独立运行。我从另一家主机提供商那里购买了一个自定义域,并使用heroku自定义域选项将DNS指向我的网站。

有关我的设置的技术详细信息

  • NodeJS服务器:Express
  • NodeJS版本:v10.15.0
  • React版本:v16.2.0
  • 自定义域:www.tabbs.nl
  • Heroku域名:tabbs-web-app.herokuapp.com

我遇到的问题

为了为react/NodeJS设置SSL,我一直在研究很多文档和教程,但找不到关于如何为我的设置设置SSL/安全性的像样的教程。

我已经读过的教程:

  • Node+Express+Lets Encrypt
  • 如何将SSL/TLS与nodejs一起使用
  • 堆栈溢出的帖子,可能还有更多我现在忘记的东西

我想要实现什么

我想实现的目标是在React web应用程序(前端)和NodeJS API(后端)之间建立一个安全的连接,以便它们之间的所有数据都是加密和安全的。此外,我希望我的自定义域(由不同于Heroku的托管提供商购买)是安全的,并强制使用https。

如有任何问题或其他信息,请随时询问!

您尝试过在节点中使用https模块吗?

你可以这样做:

var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

express()返回的应用程序实际上是一个JavaScript函数,设计用于将其作为回调传递到Node的HTTP服务器以处理请求。这样就可以很容易地为应用程序的HTTP和HTTPS版本提供相同的代码库,因为应用程序不会从中继承(它只是一个回调。

如果您正在使用create-react应用程序,请打开您的终端并键入"npmrun-build"。这将创建一个包含所有静态文件的构建文件夹。

现在返回到您的节点后端服务并添加以下内容:

var express = require('express');
var path = require('path');
var https = require('https');
var http = require('http');
var app = express();
const options = {
key: fs.readFileSync("/srv/www/keys/my-site-key.pem"),
cert: fs.readFileSync("/srv/www/keys/chain.pem")
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

如果你正在使用react路由器为你的网络应用程序处理路由,那么你会修改GET请求如下:

var express = require('express');
const path = require('path');
var https = require('https');
var http = require('http');
var app = express();
const options = {
key: fs.readFileSync("/srv/www/keys/my-site-key.pem"),
cert: fs.readFileSync("/srv/www/keys/chain.pem")
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

这不是一个复杂的问题,不用担心ssl,只需为Node.JS/Express创建自己的证书就足够了。

React有一种内置的api调用方法

将这一行添加到React安装的package.json中,

"proxy": "http://localhost:8000/"

然后像这样调用api服务,

//Generic API Call
callApi = async () => {
const response = await fetch('/api/hello');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
// A Submit handler to proxy
handleSubmit = async e => {
e.preventDefault();
const response = await fetch('/api/myrequest', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ post: this.state.post }),
});
const body = await response.text();
this.setState({ responseToPost: body });
};

一切都有效。

最新更新