简体   繁体   English

Node.js Express API “无法获取”所有路线。 适用于本地主机但不适用于我的服务器

[英]Node.js Express API “Cannot GET” with all routes. Works on localhost but not my server

My current code is:我目前的代码是:

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 + '!');
});

The above code works as intended on localhost but when deployed onto the server I'm using, I get the following error:上面的代码在本地主机上按预期工作,但是当部署到我正在使用的服务器上时,我收到以下错误:

Cannot GET /api无法获取 /api

Failed to load resource: the server responded with a status of 404 (Not Found)加载资源失败:服务器响应状态为 404(未找到)

For this to work on any server you will have to define your port.为了在任何服务器上工作,您必须定义您的端口。

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 + '!');
});

As I can see in your code you can access server it is on 3000正如我在您的代码中看到的,您可以访问位于3000上的服务器

or if you have .env或者如果你有.env

You have to explicitly define your port number您必须明确定义您的端口号

PORT=80 //this may change depending on your choice

then access your server http://<address>:port然后访问您的服务器http://<address>:port

app.listen(port, <your public ip>, () => {
   console.log('App listening on ' + port + '!'); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM