我想创建一个简单的Express &Ubuntu 18.04上的Node应用程序,应该像API一样运行。问题是,每当尝试访问url时,我只得到502错误。下面是用于配置Apache和express应用本身的代码,以及来自日志的条目。
App.js
const express = require('express')
const http = require('http')
const cors = require('cors')
const app = express()
app.use(cors())
app.enable('trust proxy')
const port = 3500
app.get('/', function (req, res) {
console.log('asdfasdf')
})
http.createServer(app).listen(port, () => {
console.log('Running http server on port %s', port);
});
Apache配置(非ssl):
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/node2.domain.io
ServerName node2.domain.io
ServerAlias www.node2.domain.io
ProxyRequests Off
ProxyPreserveHost On
ProxyVia Full
<Proxy *>
Require all granted
</Proxy>
<Location />
ProxyPass https://127.0.0.1:3500/
ProxyPassReverse https://127.0.0.1:3500/
</Location>
<Directory /var/www/node2.domain.io>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
RewriteEngine on
RewriteCond %{SERVER_NAME} =node2.domain.io [OR]
RewriteCond %{SERVER_NAME} =www.node2.domain.io
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
Apache config (SSL):
</VirtualHost>
</IfModule>
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/node2.domain.io
ServerName node2.domain.io
ServerAlias www.node2.domain.io
SSLProxyEngine On
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
ProxyRequests Off
ProxyPreserveHost On
ProxyVia Full
<Proxy *>
Require all granted
</Proxy>
<Location />
ProxyPass https://127.0.0.1:3500/
ProxyPassReverse https://127.0.0.1:3500/
</Location>
<Directory /var/www/node2.domain.io>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
SSLCertificateFile /etc/letsencrypt/live/node2.domain.io/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/node2.domain.io/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>
日志条目:
AH01102: error reading status line from remote server 127.0.0.1:3500, referer: https://node2.domain.io/
^这个x 200
作为旁注,当我启动前端React应用程序时,它会正常工作。
在您的代码中,您从不返回对请求的响应:
app.get('/', function (req, res) {
console.log('asdfasdf')
})
当我们调用/
时,您告诉express执行console.log('asdfasdf')
而不执行其他操作。
返回像这样的东西,你将得到你的响应:
app.get('/', function (req, res) {
console.log('asdfasdf')
res.send('ok') // <-- add this line
})
另外,如果你想创建一个API,你可能想返回JSON响应,所以你可以使用Express的res.json()
方法:
app.get('/', function (req, res) {
console.log('asdfasdf')
res.json({
name: 'toto',
foo: 'bar'
})
})
我已经替换了http。createServer (/* . .*/)与app.listen(port),它现在工作了。