nodejs(Express)
我在用
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时编写的。
服务器.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'))
})
fetch('http://**Ther URL where my server.js is**/url',{
method: 'get',
headers: {'Content-Type': 'application/json'},
})
.then(response => response.json())
这样就可以了。
前端托管在nginx上,每当我看到我的域时,前端showsup就会显示出来,但是如果我必须将server.js与nginx托管的react应用程序放在同一个服务器上,我如何将它连接到server.js端点。我对nginx完全不熟悉,对解决这个问题没有具体的想法。我的node server.js使用pm2在服务器上运行。
但这现在用处不大,因为我的前端fetch执行的是localhost:3005/url,它在访问域的设备的3005端口中查找url点,而不是托管前端和node server.js的实际服务器。
我还试着把
localhost:3005/url
从server.js到使用服务器的ip,但只有当我使用学校的wifi连接时,这个地址才是可见的。
如果我通过数据连接从手机中更改输入该ip地址,则无法访问该地址。所以,我以为
"ipaddress:3005/url"
也不是正确的方法。我在这一点上迷失了,任何建议都会有很大帮助!!!理想情况下,我希望在服务器上的nginx上运行主机前端,并让pm2运行server.js。
我只需要一种方法来连接前端和后端的端点。我需要
我的server.js所在的URL
我的server.js所在的URL
/网址'{
method:'获取',
标题:{'Content-Type':'application/json'},
。然后(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配置目前只服务于前端。另外,在上面的代码中,real domain.com被example.com替换。