Невозможно получить данные в процессе производства из mlab / mongoose. В разработке все работает нормально - PullRequest
0 голосов
/ 24 мая 2019

Я получаю массив данных из mlab в моем файле App.js в ComponentDidMount.В разработке все работает нормально. Но в процессе извлечения mlab возвращается неопределенным.Мое приложение опубликовано на Heroku.

В моей конфигурации в Heroku я устанавливаю PROD_MONGODB & MONGODB_URI на URL-адрес mlab (mongodb: //: @d ######. mlab.com:######/

--------------------> выборка данных во внешнем интерфейсе

<code><pre>
class App extends Component {

  state = {
    isLoading: true,
    artists: [],
    login: false,
  }


  componentDidMount() {
    fetch("/api/getArtists/")
    .then(data => data.json())
    .then (console.log("in get retailer"))
    .then(res => { 
      const newArtists = res.data.sort((a, b) => (a.artist_name > b.artist_name) ? 1 : ((b.artist_name > a.artist_name) ? -1 : 0))
      this.setState({ artists: newArtists, isLoading: false })
    });
};

--------------------> Мой маршрут

<code><pre>

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
});

const PORT = process.env.PORT || 3010


mongoose.connect(
    process.env.MONGODB_URI || 'mongodb://<dbuser>:<dbpassword>@d######.mlab.com:######/<nameofdatabse>',
    { useNewUrlParser: true }
    );

app.use(cookieParser())
app.use(cors());
// app.use(express.bodyParser());

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, '/client/build')));

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('/client/public'));
    app.get('*', (req, res) => {
        res.sendFile(path.join(__dirname + '/client/build/index.html'));
    });
}


app.get("/api/getArtists", (req, res) => {
    console.log("in getArtists")
    ArtistProfile.find((err, data) => {
        if (err) return res.json({ success: false, error: err });
        return res.json({ success: true, data: data });
    }).catch() // Errors will be passed to Express.
});



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


app.listen(PORT, () => {
    console.log(`Server listen on port ${PORT}`)
})




--------------------> мой package.json в моем бэкэнде nodejs

<code>
{
  "name": "backend",
  "version": "1.0.0",
  "engines": {
    "node": "10.5.0",
    "npm": "6.1.0"
  },
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "server": "nodemon index.js",
    "client": "npm run start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "heroku-postbuild": "cd client && npm install && npm run build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^3.0.6",
    "body-parser": "^1.18.3",
    "concurrently": "^4.1.0",
    "cookie-parser": "^1.4.4",
    "cors": "^2.8.5",
    "dotenv": "^8.0.0",
    "express": "^4.16.4",
    "jsonwebtoken": "^8.5.1",
    "moment": "^2.24.0",
    "mongoose": "^5.5.0",
    "nodemailer": "^5.1.1",
    "nodemon": "^1.18.10"
  }
}


</code>

--------------------> мой package.json на стороне клиента activjs

<code>
{
  "name": "antoine",
  "version": "0.1.0",
  "private": true,
 "proxy": "http://localhost:3010",
  "dependencies": {
    "antd": "^3.10.3",
    "axios": "^0.18.0",
    "bootstrap": "^4.1.3",
    "react": "^16.6.1",
    "react-burger-menu": "^2.6.5",
    "react-document-meta": "^3.0.0-beta.2",
    "react-dom": "^16.6.1",
    "react-facebook": "^6.0.15",
    "react-helmet": "^5.2.0",
    "react-instagram-embed": "^1.4.1",
    "react-player": "^1.6.6",
    "react-reveal": "^1.2.2",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.0",
    "reactstrap": "^6.5.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "heroku-postbuild": "npm run build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-preset-env": "^1.7.0"
  }
}

</code>

Я просто хотел бы получить свои данные в производственном процессе, если они не определены, поэтому я могу что-то отобразить на моемсайт.

...