【发布时间】:2020-02-12 18:52:09
【问题描述】:
我已经制作了一个全栈应用程序,它的前端由 React 和一个用 nodejs(Express) 编写的 server.js 编写,我使用 Postgres 作为我的数据库。我以前做过一次,并在Heroku 上托管我的网站。
不同之处在于,在 Heroku 上,我的前端和后端位于不同的 Url 上,因此在我的 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 点,而不是托管前端的实际服务器和节点 server.js。
我还尝试将 server.js 中的 localhost:3005/url 替换为使用服务器的 ip,但该地址似乎只有在我使用学校的 wifi 连接时才能访问。
如果我通过数据连接从我的手机输入该 IP 地址,则无法访问该地址。所以,我认为"ipaddress:3005/url" 也不是正确的方法。我在这一点上迷路了,任何建议都会有很大的帮助!!!理想情况下,我想在服务器上的 nginx 上运行我的前端,并让 pm2 运行 server.js。
我只需要一种方法来连接前端和后端的端点。我需要
我的 server.js 所在的 URL
fetch('http://我的 server.js 所在的网址/url',{ 方法:'得到', 标头:{'Content-Type': 'application/json'}, }) .then(response => 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。
谢谢!
【问题讨论】:
-
另外,我只能通过ssh访问学校服务器。
标签: javascript node.js reactjs nginx web-deployment