首页 > 解决方案 > 带有所有路由的 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(未找到)

标签: node.jsexpress

解决方案


为了在任何服务器上工作,您必须定义您的端口。

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


推荐阅读