javascript - 在同一台服务器上托管 React 前端和 NodeJs 后端
问题描述
我已经制作了一个全栈应用程序,它的前端由 React 和 server.js 编写,nodejs(Express)
我将Postgres
其用作我的数据库。我以前做过一次,并将我的网站托管在Heroku
.
不同之处在于,在 Heroku 上,我的前端和后端位于不同的 Urls 上,因此在我的 react 应用程序中我可以做到
fetch('http://localhost:3005/url',{
method: 'get',
headers: {'Content-Type': 'application/json'},
})
.then(response => response.json())
上面的代码是当我通过 npm start 在我的笔记本电脑上运行我的 react 和 node 时。
我的server.js将是
app.get('/url', (req, res) => {
db.insert({
page_url: req.body.urlInfo,
user_visit_id: req.body.visitID,
})
.into('pageurl')
.then((id) => {
res.json(id);
}).catch(err => res.status(400).json('unable to write'))
})
在 Heroku 中,我只需将前端 React 行更改为:
fetch('http://**Ther URL where my server.js is**/url',{
method: 'get',
headers: {'Content-Type': 'application/json'},
})
.then(response => response.json())
这将运行得非常好。现在问题来了,我必须将应用程序部署到学校服务器。服务器运行了 nginx,并且我已获得该项目的域。
前端托管在 nginx 上,每当我访问我的域时,前端就会显示,但是我如何将它连接到我的 server.js 端点,因为我必须将 server.js 与托管的 react 应用程序放在同一台服务器中通过 nginx。我对 nginx 完全陌生,对解决问题没有具体的想法。我让我的节点 server.js 使用 pm2 在服务器上运行。
但这现在用处不大,因为我的前端获取 localhost:3005/url 会在访问域的设备的端口 3005 中查找 url 点,而不是托管前端和节点服务器的实际服务器.js。
我还尝试将localhost:3005/url
server.js 替换为使用服务器的 ip,但如果我在学校的 wifi 连接上,该地址似乎只能访问。
如果我通过数据连接更改从手机输入该 IP 地址,则无法访问该地址。所以,我认为这"ipaddress:3005/url"
也不是正确的方法。我在这一点上迷路了,任何建议都会有很大的帮助!!!理想情况下,我想在服务器上的 nginx 上运行我的前端,并让 pm2 运行 server.js。
我只需要一种方法来连接前端和后端的端点。我需要
我的 server.js 所在的 URL
fetch('http://我的 server.js 是/url',{ 方法: 'get', headers: {'Content-Type': 'application/json'}, }) .then(response =>响应.json())
我的 nginx 配置文件现在看起来像这样:
server {
listen 80;
listen [::]:80;
root /var/www/example.com/html/build;
index index.html index.php index.htm index.nginx-debian.html;
server_name example.com www.example.com;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php-fpm (or other unix sockets):
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
# With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
}
location / {
try_files $uri /index.html;
#try_files $uri $uri/ =404;
}
}
此 nginx 配置目前仅服务于前端。此外,在上面的代码中,真正的 domain.com 被替换为 example.com。
谢谢!
解决方案
我要做的是在不同端口上的 nginx 中设置一个虚拟主机,它将所有请求代理到您的 nodejs 应用程序,例如:
server {
listen 8080;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3005;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
在这个例子中,做了以下假设:
- example.com 是学校分配给您项目的域
- 端口 8080 是您将在首页中打开和设置的端口:
fetch('http://example.com:8080', {})
- 您的 nodejs 应用程序在端口 3005 上运行
推荐阅读
- javascript - 从字段中动态读取值
- python - Tkinter:如何更改画布中的图像
- ios - 金属多个计算着色器与单个
- java - 使用 jsoup 进行解析。我尝试从没有 id 的元素中提取文本,但它似乎不起作用
- c++ - Sonarqube 如何理解分支覆盖率
- oracle - 在结果集中生成动态列
- gdb - 将 ELF 加载到目标时 GDB 跳过填充
- c# - RichTextBox 打印结果的时间过长
- javascript - 使用 jQuery/Javascript 的 DOM 事件仅适用于 $().ready 或 window.onload
- ms-query - 在 MS Query 中获取分隔符之间第 n 次出现的单词