微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

后端节点请求可在localhost上运行,但不适用于Heroku部署

如何解决后端节点请求可在localhost上运行,但不适用于Heroku部署

我一直在使用基本的MERN应用(练习追踪器)练习部署到Heroku。您可以看到页面here。目前,UI正常工作,但对后端的每个请求均遇到503错误。在花了三个小时进行谷歌搜索并尝试解决问题之后,我认为我应该咨询stackOverflow。

在我当前的项目中,我的所有工作都在本地主机上进行,但在heroku中却没有。我可以解决与MongoDB的连接问题,因为它在本地可用。现在,我的直觉是问题出在我的后端package.json文件,server.js文件procfile或config.js中。

我仍在学习与Node一起工作,所以即使您不能告诉我答案,但可以告诉我一些我应该采取的措施以排除故障,我还是会很感激的。

如果您想在github上看到我的完整代码,则可以here看到它。

这是我在heroku日志中收到的错误消息的示例。

2020-09-01T13:24:28.665631+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/exercises/" host=exercise-tracker-deployment-3.herokuapp.com request_id=f2b3dfaa-3e08-449a-b3a4-453ca864cc0f fwd="129.137.144.10" dyno=web.1 connect=1ms service=30001ms status=503 bytes=0 protocol=https

这是我当前用于后端的package.json

{
  "name": "backend","version": "1.0.0","description": "","main": "index.js","scripts": {
    "test": "echo \"Error: no test specified\" && exit 1","build": "cd client && npm run build","install-client": "cd client && npm install","heroku-postbuild": "cd client && npm install && npm run build","start": "node server.js","client": "cd client && npm start","dev": "concurrently -n 'server,client' -c 'red,green'  \"nodemon server.js\" \"npm run client\""
  },"author": "","license": "ISC","dependencies": {
    "cors": "^2.8.5","dotenv": "^8.2.0","express": "^4.17.1","mongoose": "^5.10.0"
  }
}

这是我的server.js

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


require('dotenv').config();


    const app = express();
    const port = process.env.PORT || 5000;
    
    
    app.use(cors());
    app.use(express.json());
    app.use(express.static('client/build'))
    
    const uri = process.env.ATLAS_URI;
            
    mongoose.connect(uri,{ useNewUrlParser: true,useCreateIndex: true }
    );
    const connection = mongoose.connection;
    
    
    connection.once('open',() => {
      console.log("MongoDB database connection established successfully");
    })
    
    const exercisesRouter = require('./routes/exercises');  
    const usersRouter = require('./routes/users');  
    
    app.use('/exercises',exercisesRouter);  
    app.use('/users',usersRouter);
    
    app.listen(port,() => {
    console.log(`Server is running on port: ${port}`);
    });

这是我非常基本的procfile

web: npm start

这是我的config.js

import dotenv from 'dotenv'
dotenv.config();

export const BACKEND_URL = process.env.NODE_ENV === 'development'? "http://locahost:5000" : "https://exercise-tracker-deployment-3.herokuapp.com/" 

解决方法

我遇到了类似的问题,而解决方案实际上是因为在MongoDB Atlas->网络访问-> IP白名单中,我没有添加0.0.0.0/0作为新IP地址。

添加此代码后,代码将平稳运行。

还要检查您正在使用的集合和数据库是否已经在群集中创建,即使它们为空。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。