Мое приложение MERN работает только в Chrome. Как заставить его работать во всех браузерах и на всех устройствах? - PullRequest
0 голосов
/ 07 августа 2020

У меня есть приложение MERN с Redux, развернутое в Digital Ocean, Ubuntu 18.04 Droplet, которое должно быть полностью развернуто, но оно работает только в моем Chrome браузере. Я думаю, что это может работать только потому, что браузер Chrome имеет расширение Redux, но я не знаю.

Я успешно развернул приложение React с серверной частью, подобной этому, на Digital Ocean Droplet, но у него не было MongoDB или Redux. Я установил MongoDB, и Redux должен быть установлен нормально со всем остальным, поэтому я не знаю, в чем проблема. Mon go и Redux работают нормально, когда сайт открыт в браузере Chrome. Я поднимаю это, потому что, возможно, если вы знаете, что при добавлении Mon go и Redux в приложение в капле требуется настройка, вы можете просто поделиться этой информацией, чтобы вам не пришлось просеивать все данные ниже.

Когда я захожу на сайт на своем iPhone, он ничего не отображает. Если я захожу на сайт в Firefox, значок сайта загружается, но экран остается пустым. В консоли Firefox вижу ошибку ... Uncaught TypeError: t is undefined. Не знаю, откуда эта ошибка. Я никогда не вижу его на Chrome, когда я захожу на сайт.

Я не знаю, нужно ли мне делать что-то другое для развертывания приложения для «производства». Возможно, это как-то связано с проблемой.

Возможно, ошибка как-то связана с конфигурацией Nginx. Это мой Nginx файл по умолчанию ...

# 159.203.45.100 is where I go to visit the site

server {
    listen 80;
    server_name 159.203.45.100;
    root /var/www/MERN_App/client/build;

    error_page 404 /index.html;

    location / {
        add_header Cache-Control no-cache;
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Host $remote_addr;
        proxy_pass http://localhost:5002;
    }
}

Вот мой server.js файл. (У меня pm2 обрабатывает его)

const express = require('express');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const path = require('path');
const app = express();
const jwt = require('jsonwebtoken')
const config = require('config')

// Middleware
app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.use(express.urlencoded({ extended: true }));

app.use(function (req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);
  // Pass to next layer of middleware
  next();
});

// Use Routes
app.use('/api/items', require('./routes/api/items'));
app.use('/api/users', require('./routes/api/users'));
app.use('/api/auth', require('./routes/api/auth'));
app.use('/api/comments', require('./routes/api/comments'));

if (process.env.NODE_ENV === 'production') {
  // Set static folder
  app.use(express.static('client/build'));

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

const port = process.env.PORT || 5002;
app.listen(port, () => console.log(`Server started on port ${port}`));  

Вот что отображает pm2 show 0 ...

    $ pm2 show 0
    Describing process with id 0 - name server 
    ┌───────────────────┬────────────────────────────────────────┐
    │ status            │ online                                 │
    │ name              │ server                                 │
    │ namespace         │ default                                │
    │ version           │ 1.0.0                                  │
    │ restarts          │ 0                                      │
    │ uptime            │ 3h                                     │
    │ script path       │ /var/www/MERN_App/server.js            │
    │ script args       │ N/A                                    │
    │ error log path    │ /home/sammy/.pm2/logs/server-error.log │
    │ out log path      │ /home/sammy/.pm2/logs/server-out.log   │
    │ pid path          │ /home/sammy/.pm2/pids/server-0.pid     │
    │ interpreter       │ node                                   │
    │ interpreter args  │ N/A                                    │
    │ script id         │ 0                                      │
    │ exec cwd          │ /var/www/MERN_App                      │
    │ exec mode         │ fork_mode                              │
    │ node.js version   │ 10.22.0                                │
    │ node env          │ N/A                                    │
    │ watch & reload    │ ✘                                      │
    │ unstable restarts │ 0                                      │
    │ created at        │ 2020-08-06T20:33:15.884Z               │
    └───────────────────┴────────────────────────────────────────┘
    Revision control metadata 
    ┌──────────────────┬────────────────────────────────────────────────┐
    │ revision control │ git                                            │
    │ remote url       │ https://github.com/MotorCityCobra/MERN_App.git │
    │ repository root  │ /var/www/MERN_App                              │
    │ last update      │ 2020-08-06T20:29:37.883Z                       │
    │ revision         │ 2613e5273955e382a6fd08d023ba1f403d9a3daf       │
    │ comment          │ first commit                                   │
    │ branch           │ master                                         │
    └──────────────────┴────────────────────────────────────────────────┘
    Actions available 
    ┌────────────────────────┐
    │ km:heapdump            │
    │ km:cpu:profiling:start │
    │ km:cpu:profiling:stop  │
    │ km:heap:sampling:start │
    │ km:heap:sampling:stop  │
    └────────────────────────┘
    Trigger via: pm2 trigger server <action_name>

    Code metrics value 
    ┌────────────────────────┬───────────┐
    │ Heap Size              │ 33.25 MiB │
    │ Heap Usage             │ 84.57 %   │
    │ Used Heap Size         │ 28.12 MiB │
    │ Active requests        │ 0         │
    │ Active handles         │ 13        │
    │ Event Loop Latency     │ 0.84 ms   │
    │ Event Loop Latency p95 │ 4.93 ms   │
    │ HTTP Mean Latency      │ 30 ms     │
    │ HTTP P95 Latency       │ 57 ms     │
    │ HTTP                   │ 0 req/min │
    └────────────────────────┴───────────┘
    Divergent env variables from local env 
    ┌────────────────┬──────────────────────┐
    │ SSH_CONNECTION │ 75.118.134.38 37152  │
    │ XDG_SESSION_ID │ 23                   │
    │ PWD            │ /var/www/MERN_App    │
    │ SSH_CLIENT     │ 75.118.134.38 37152  │
    │ SSH_TTY        │ /dev/pts/0           │
    └────────────────┴──────────────────────┘

    Add your own code metrics:
    Use `pm2 logs server [--lines 1000]` to display logs
    Use `pm2 env 0` to display environment variables
    Use `pm2 monit` to monitor CPU and Memory usage server

Вот мой package.json для сервера ...

{
  "name": "meme_hole",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "client-install": "npm install --prefix client",
    "start": "node server",
    "server": "nodemon server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "build": "npm install && npm install --prefix client && npm audit fix && npm audit fix --prefix client && npm run build --prefix client",
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "concurrently": "^4.1.2",
    "config": "^3.3.1",
    "connect-flash": "^0.1.1",
    "express": "^4.17.1",
    "gridfs-stream": "^1.1.1",
    "jsonwebtoken": "^8.5.1",
    "method-override": "^3.0.0",
    "mongoose": "^5.9.22",
    "multer": "^1.4.2",
    "multer-gridfs-storage": "^3.3.0",
    "prop-types": "^15.7.2",
    "react-infinite-scroll-component": "^4.5.3",
    "react-redux": "^7.2.0",
    "react-router-dom": "^5.2.0",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0",
    "serve-index": "^1.9.1",
    "stripe": "^8.81.0",
    "uuid": "^3.4.0"
  },
  "devDependencies": {
    "nodemon": "^1.19.4"
  }
}

Моя Mon go версия ...

$ mongo --eval 'db.runCommand({ connectionStatus: 1 })'
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
{
    "authInfo" : {
        "authenticatedUsers" : [ ],
        "authenticatedUserRoles" : [ ]
    },
    "ok" : 1
}

Моя версия Node: v10.22.0

Я полагаю, что установил все в соответствии с лучшими практиками. Я запустил их в каталоге, в котором находится сборка ...

sudo gpasswd -a "$USER" www-data
sudo chown -R "$USER":www-data /var/www
find /var/www -type f -exec chmod 0660 {} \;
sudo find /var/www -type d -exec chmod 2770 {} \;

Я следовал всем руководствам Digital Ocean по настройке сервера и всего остального. Начальная установка сервера с Ubuntu 18.04 Как установить Nginx на Ubuntu 18.04 Как установить Node.js на Ubuntu 18.04 Как установить MongoDB в Ubuntu 18.04

Спасибо за чтение!

1 Ответ

1 голос
/ 07 августа 2020

Я посетил сайт в крайнем состоянии, и он не работал, пока я не установил расширение, так что вы правы, что расширение заставляет его работать. Но у меня другая ошибка: Uncaught TypeError: Cannot read property 'apply' of undefined. Похоже, что есть магазин. js файл пытается запустить const store = createStore (... но createStore не определен.

Согласно этой ссылке, https://github.com/zalmoxisus/redux-devtools-extension/issues/320, вы можете попробовать добавить window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose в свой store.js файл.

Если вы добавите его к тому, что у вас уже есть, у вас будет следующее: window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() || window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose)); Я думаю, это делает он работает с расширением и без него.

...