【问题标题】:my app have a problem after i refresh the page刷新页面后我的应用出现问题
【发布时间】:2020-09-04 20:57:00
【问题描述】:

当我第一次打开我的应用程序时它工作得很好但是当我刷新页面时它给了我一个指向我的 index.html 文件 (/client/build/index.html) 的 url,我已经将它部署在 heroku

这是我的 app.js 文件中创建服务器的代码

const express = require('express');
const app = express();
const path = require('path');

// create a server for socket io

    const http = require('http');
    const socketio = require('socket.io');
    const server = http.createServer(app);
    module.exports = io = socketio(server);

    // my middle ware
    const morgan = require('morgan');
    const bodyParser = require('body-parser');

    // Init Middelware
    app.use(express.json({ extended: false }));

    // my router
    const postRoute = require('./nodeapi/routers/post');
    const authRouter = require('./nodeapi/routers/auth');
    const usersRouter = require('./nodeapi/routers/users');
    const friendRouter = require('./nodeapi/routers/friend');
    const chatRouter = require('./nodeapi/routers/chats');
    const mongoDB = require('./nodeapi/mongodb-database/db');
    const port = process.env.PORT;

    // Connect monogo database
    mongoDB();

    // Middel ware
    app.use(morgan('dev'));
    app.use(bodyParser.json());

    // Get the routes
    app.use('/', postRoute);
    app.use('/', authRouter);
    app.use('/', usersRouter);
    app.use('/', friendRouter);
    app.use('/', chatRouter);
    app.use('/file/', express.static('./uploads/'));

    // connect to socket io
    io.on('connection', (socket) => {});
    //Serve static assets in productio
    if (process.env.NODE_ENV === 'production') {
      // Set static folder
      app.use(express.static('./client/build'));
      app.get('*', (req, res) => {
        res.send(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
      });
    }
    // listen to the port
    server.listen(port, () => {
      console.log(`this is port ${port}`);
    });

这是我第一次打开它的时候

这是我刷新页面的时候

【问题讨论】:

    标签: node.js reactjs express heroku


    【解决方案1】:

    您只需将其作为文件而不是文本发送

    app.use(express.static('./client/build'));
    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
    });
    

    【讨论】:

    • 我做了你上面说的解决方案,它给了我这个错误(内部服务器错误)@Ahmed Hamed
    • @mohamednageh 是的,我的错,我编辑了代码。希望它现在可以工作。
    • 我试过了,但刷新页面后却找不到
    • @mohamednageh 你能发布项目文件结构吗?
    • 它工作我编辑 index.html 文件方向,我会像这样 res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));非常感谢艾哈迈德
    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2017-04-17
    相关资源
    最近更新 更多