node.js - 带有所有路由的 Node.js Express API“无法获取”。适用于本地主机但不适用于我的服务器
问题描述
我目前的代码是:
var express = require('express');
const app = express();
var port = process.env.PORT || 3000;
app.get('/', function(req, res, next) {
res.redirect('/api')
});
app.get('/api', function (req, res) {
res.json({
text: 'my api!'
})
});
app.listen(port, function () {
console.log('App listening on ' + port + '!');
});
上面的代码在 localhost 上按预期工作,但是当部署到我正在使用的服务器上时,我收到以下错误:
无法获取 /api
加载资源失败:服务器响应状态为 404(未找到)
解决方案
为了在任何服务器上工作,您必须定义您的端口。
var express = require('express');
const app = express();
var port = process.env.PORT || 3000;
app.get('/', function(req, res, next) {
res.redirect('/api')
});
app.get('/api', function (req, res) {
res.json({
text: 'my api!'
})
});
//You can bind the IP address using the following code
app.listen(port, '<ip>', function () {
console.log('App listening on ' + port + '!');
});
正如我在您的代码中看到的,您可以访问它所在的服务器3000
或者如果你有.env
您必须明确定义您的端口号
PORT=80 //this may change depending on your choice
然后访问您的服务器http://<address>:port
推荐阅读
- google-cloud-data-fusion - Cloud Datafusion 中的 SPARK 加入策略
- cloud - RHV 和 OpenStack 有什么区别
- shell - Testing the Success of a Command Involving Pipes
- logstash - 在生产环境中部署 Logstash
- jenkins - 配置更改后对 In progress Build 的影响
- python - 将 float64 转换为 int(excel 到 pandas)
- sprite - 如何让一个精灵跟随 Java 中的另一个精灵?
- android - 如何在 Firestore 中为 Android 创建本地化数据方案(按语言)?
- mysql - 未找到 XAMPP MYSQL
- python - 为什么 django rest api root 没有列出经典端点