当前位置: 首页 > 知识库问答 >
问题:

React Express路由在本地有效,但在Heroku上无效

端木震博
2023-03-14

开发了一个使用路由器文件reformback.router.js的应用程序。我已将服务器设置为导入此路由器文件并将其用于“/反馈”请求。

我使用各种GET、POST、DELETE、PUT路由与数据库通信。在本地,我的app axios请求被正确路由,并与我的数据库正确集成。在我的服务器上。在js文件中,我阅读了其他问题,并实现了我认为express应该为生产版本提供的功能。当我在Heroku上运行应用程序时,我从任何axios请求中收到的响应似乎都是HTML文件,这表明无法识别该路线,但我无法确定错误。我相信我为Heroku正确设置了数据库,尽管问题可能就在那里。

这突出的一个间接问题是,一旦部署在Heroku上,我就不知道如何对这些类型的请求进行故障排除。我已经将它与Github上的存储库连接起来,但找不到任何“服务器终端”来协助错误搜索。非常欢迎有关如何使用Heroku进行此故障排除的任何建议。

更新以包括GET和POST请求的Heroku日志:

2018-11-04T03:20:11.564616 00:00 heroku[路由器]: at=info方法=POST路径="/反馈"主机=prime-feedback-app.herokuapp.comrequest_id=65732134-d050-4f82-ab08-9d0764266cb3 fwd="73.242.14.56"dyno=web.1连接=0ms服务=3ms状态=200字节=2377协议=https

2018-11-04T03:21:05.866976 00:00 heroku[router]: at=info method=GET path=“/feedback” host=prime-feedback-app.herokuapp.com request_id=6b1b7341-5dbf-443d-bff4-e0a6e3080e51 fwd=“73.242.14.56” dyno=web.1 connect=0ms service=3ms status=200 bytes=2377 protocol=https

我已经包含了我认为可能有用的文件。

文件结构(星号表示文件夹)

feedback-app
    **build**
    **public**
    **server**
        **modules**
             pool.js
        **routes**
             feedback.router.js
        server.js
    **src**
        **components**
             ...
        index.js
        registerServiceWorker.js
     data.sql
     package.json
     package-lock.json

我的axios请求示例:

axios({
    method: 'GET',
    url: '/feedback'
}).then((response) => {
    console.log('response:',response);
    this.setState({
        display: 'all',
        feedback: response.data
    });
}).catch((error) => {
    console.log('error',error);
})

服务器.js

    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    const path = require('path');
    const PORT = process.env.PORT || 5000;
    const feedbackRouter = require('./routes/feedback.router');

    /** ---------- MIDDLEWARE ---------- **/
    app.use(bodyParser.json()); // needed for angular requests
    app.use(bodyParser.urlencoded({extended: true}));

    if (process.env.NODE_ENV === 'production') {
        // Exprees will serve up production assets
        app.use(express.static(path.join(__dirname, 'build')));

        // Express serve up index.html file if it doesn't recognize route
        app.get('*', (req, res) => {
          res.sendFile(path.join(__dirname, 'build', 'index.html'));
        });
    }

    /** ---------- EXPRESS ROUTES ---------- **/
    app.use('/feedback', feedbackRouter);

    /** ---------- START SERVER ---------- **/
    app.listen(PORT, () => {
        console.log('Listening on port: ', PORT);
    });

游泳池.js

const pg = require('pg');
const url = require('url');
let config = {};

if (process.env.DATABASE_URL) {
    // Heroku gives a url, not a connection object
    // https://github.com/brianc/node-pg-pool
    let params = url.parse(process.env.DATABASE_URL);
    let auth = params.auth.split(':');

    config = {
        user: auth[0],
        password: auth[1],
        host: params.hostname,
        port: params.port,
        database: params.pathname.split('/')[1],
        ssl: true, // heroku requires ssl to be true
        max: 10, // max number of clients in the pool
        idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
    };

} else {
    // only change the things on the right side of the ||
    config = {
        user: process.env.PG_USER || null, //env var: PGUSER
        password: process.env.DATABASE_SECRET || null, //env var: PGPASSWORD
        host: process.env.DATABASE_SERVER || 'localhost', // Server hosting the postgres database
        port: process.env.DATABASE_PORT || 5432, //env var: PGPORT
        database: process.env.DATABASE_NAME || 'prime_feedback', //env var: PGDATABASE or the name of your database (e.g. database: process.env.DATABASE_NAME || 'koala_holla',)
        max: 10, // max number of clients in the pool
        idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
    };
}

module.exports = new pg.Pool(config);

package.json

{
  "name": "react-reflection-board",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:5000",
  "engines": {
    "npm": "6.4.1",
    "node": "10.11.0"
  },
  "dependencies": {
    "@material-ui/core": "^3.3.2",
    "@material-ui/icons": "^3.0.1",
    "axios": "^0.17.1",
    "bootstrap": "^4.1.3",
    "pg": "^7.4.1",
    "react": "^16.3.0",
    "react-confirm-alert": "^2.0.6",
    "react-dom": "^16.3.0",
    "react-progressbar": "^15.4.1",
    "react-redux": "^5.1.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "^2.1.1",
    "react-swal": "^3.0.0",
    "reactstrap": "^6.5.0",
    "recompose": "^0.30.0",
    "redux": "^4.0.1",
    "redux-logger": "^3.0.6",
    "serve": "^10.0.2"
  },
  "devDependencies": {
    "nodemon": "^1.18.5"
  },
  "scripts": {
    "dev": "react-scripts start",
    "start": "serve -s build",
    "build": "react-scripts build",
    "heroku-postbuild": "npm run build",
    "client": "react-scripts start",
    "server": "nodemon --watch server server/server.js",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

feedback.router.js

    const express = require('express');
    const router = express.Router();
    const pool = require('../modules/pool');

    // GET feedback
    router.get('/', (req, res) => {
        // Request all entered feedback and return them
        pool.query('SELECT * FROM feedback ORDER BY id DESC;')
            .then((result) => {
                res.send(result.rows);
            }).catch((error) => {
                console.log('Error GET /api/feedback', error);
                res.sendStatus(500);  
        });
    })

    // GET feedback
    router.get('/flagged', (req, res) => {
        // Request all entered feedback and return them
        pool.query('SELECT * FROM feedback WHERE flagged = true ORDER BY id DESC;')
            .then((result) => {
                res.send(result.rows);
            }).catch((error) => {
                console.log('Error GET /api/feedback/flagged', error);
                res.sendStatus(500);  
        });
    })

    // POST new feedback entry
    router.post('/', async (req, res) => {
        const client = await pool.connect();

        try {
            const {
                feeling,
                understanding,
                support,
                comments,
                flagged
            } = req.body;
            await client.query('BEGIN')
            const orderInsertResults = await client.query(`INSERT INTO feedback ("feeling","understanding","support","comments","flagged")
            VALUES ($1, $2, $3, $4, $5);`, [feeling, understanding, support, comments, flagged]);

            await client.query('COMMIT')
            res.sendStatus(201);
        } catch (error) {
            await client.query('ROLLBACK')
            console.log('Error post /api/feedback', error);
            res.sendStatus(500);
        } finally {
            client.release()
        }
    });

    // DELETE a feedback entry
    router.delete('/:id', (req, res) => {
        pool.query('DELETE FROM feedback WHERE id=$1', [req.params.id]).then((result) => {
            res.sendStatus(200);
        }).catch((error) => {
            console.log('Error delete /api/feedback', error);
            res.sendStatus(500);
        })
    });

    // PUT / update a feedback entry
    router.put('/:id', (req,res) => {
        let feedbackId = req.params.id;
        let updatedFlagStatus = req.body.updatedFlagStatus;
        console.log('to update flag of item',feedbackId,'to',updatedFlagStatus);
        const sqlText = `UPDATE feedback SET flagged = $2 WHERE id=$1`;
        console.log('sqlText:',sqlText);
        pool.query(sqlText,[feedbackId, updatedFlagStatus])
            .then( (result) => {
                console.log('successfully updated flag status', result);
                res.sendStatus(200);
            })
            .catch( (error) => {
                console.log('error updating flag status', error);
                res.sendStatus(500);
            })
    })

    module.exports = router;

共有1个答案

方玄天
2023-03-14

每当您使用Express为React ReactRouter应用程序提供服务时,您都会遇到Express routing和ReactRouter“冲突”的情况。

在生产环境中,您的Express服务器将“提供index.html文件,如果它不能识别路由”,因此当您请求/反馈时,第一个匹配项是行app.get('*'...,这就是为什么您的Ajax请求实际上返回了index.html文件。

if (process.env.NODE_ENV === 'production') {
    // Exprees will serve up production assets
    app.use(express.static(path.join(__dirname, 'build')));

    // Express serve up index.html file if it doesn't recognize route
    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'build', 'index.html'));
    });
}

/** ---------- EXPRESS ROUTES ---------- **/
app.use('/feedback', feedbackRouter);

将您的<代码>应用程序放入。使用(“/反馈”,反馈路由器) 行,应该可以工作。

现在,您应该完全安装"Heroku Toolband"https://devcenter.heroku.com/articles/heroku-cli这样您就可以在终端上运行heroku logs-t来调试您的服务器端代码。

希望有帮助!

 类似资料:
  • 我已经在localhost上运行了我的应用程序,一切都运行得很好,但是一旦我部署到heroku上,主页就可以正常工作了,但是当我点击“my-app/stocks/aapl”时,我得到了404。我查看了其他有此问题的人,并添加了一个static.json文件,但这没有帮助。我已经从我的server.js中粘贴了我的代码、我的文件夹结构、static.json和我的app.js以供参考。 static

  • 问题内容: 在这里反应/反应路由器/ heroku问题(可能是出现故障的heroku)。 我正在关注这个精彩的教程:https : //medium.com/@patriciolpezjuri/using-create-react-app-with-react-router- express- js-8fa658bf892d#.y77yjte2j ,一切正常,直到我发布为止它到heroku,我尝试

  • 我有一个命令,用FFmpeg生成一个带有背景和文本的视频,并希望使用Azure批处理服务来呈现它。在本地“我的命令”有效: ./ffmpeg-f lavfi-i color=c=green:s=854x480:d=7-vf“[in]drawtext=fontsize=46:fontcolor=white:text=dfdhjf dhjfh djfh:x=(w-text_w)/2:y=((h-tex

  • 我使用devise gem with rails进行身份验证,我的应用程序在本地运行良好,但是在heroku上部署时无法访问device视图。 检查日志时出现以下错误: ←[app[web.1]:←[0mDevis处理e::SessionsController#新作为超文本标记语言 ←[app[web.1]:←[0mDevis处理e::SessionsController#新作为超文本标记语言 ←

  • 我有这个简单的代码: 这在本地主机上效果很好,并导致: 但是当我在Heroku上使用它时,我得到了一个应用程序错误。日志状态: 2018-09-12t 13:50:25.541953 00:00 heroku[web . 1]:状态从启动更改为崩溃 2018-09-12T13:50:32.696713 00:00 heroku[router]: at=error code=H10 desc=“Ap

  • 图像的html代码 heroku bash显示Howling.jpg