【问题标题】:NodeJS doesn't work on Heroku but work at localhostNodeJS 不能在 Heroku 上运行,但可以在 localhost 上运行
【发布时间】:2021-11-23 11:54:19
【问题描述】:

我向 Heroku 部署了一个简单的快速 NodeJS 应用程序,但它不起作用,

它能够加载根 URL:https://fathomless-bayou-36989.herokuapp.com/,但不能加载像 https://fathomless-bayou-36989.herokuapp.com/token 这样的其他 URL。它返回 503 错误。

这是我的 app.js:

const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extends:true }));

app.get("/", function (req, res) {
    res.send("<h1>Hello There!</h1><p>This is server to save token for Dyad app by Dai Vuong.</p>")
})

dotenv.config ();

mongoose.connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

// Token Object
const Token = mongoose.model('token', new mongoose.Schema (
    {
        number: { type: Number, default: 100},
        tokenID: String,
    }
));

// Get all tokens
app.get('/token', async (req, res) => {
    const tokens = await Token.find()
    res.send(tokens);
})

// Get token by number
app.get('/token/:number', async (req, res) => {
    const tokens = await Token.find({number:req.params.number})
    res.send(tokens);
})

// Add new token
app.post('/token', async (req, res) => {
    const lastToken = await Token.find().sort({ number: -1 }).limit(1);
    const lastNumber = lastToken.length === 0  ? 0 : lastToken[0].number;
    if (!req.body.token){
        return res.send({ message: 'Data is required.'});
    }
    const token = await Token({ ...req.body, number: lastNumber + 1 }).save();
    res.send(token);
});


const port = process.env.PORT || 5000;

app.listen(port, () => {
    console.log(`Serve running at port:${port}`);
});

这是我的 package.json:

{
  "name": "DyadServer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Dai Vuong",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "mongoose": "^6.0.8"
  }
}

我试着像人们说的那样添加app.yaml 我还尝试在heroku run bash 中创建.env 以添加云mongodb 数据库连接 但它仍然无法正常工作。 请帮帮我!

【问题讨论】:

    标签: node.js api express heroku mongoose


    【解决方案1】:

    Express 会按照您在程序中注册的顺序处理 /、/token 和 /token/42 等路由。

    因此,您的 / 路由正在使用您对 /token 的请求。把最具体的路线放在第一位。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      相关资源
      最近更新 更多