Skip to content

Commit

Permalink
Свяжет фронт-сервер и апи-сервер, добавит отображение страниц в браузере
Browse files Browse the repository at this point in the history
  • Loading branch information
Leks511 committed Aug 24, 2021
1 parent 857c7fa commit 772b4ac
Show file tree
Hide file tree
Showing 20 changed files with 339 additions and 155 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ node_modules/

# Папка с собранными файлами проекта
build/

# Папка с загруженными изображениями
src/express/upload/img/*.*
157 changes: 148 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"server": "nodemon ./src/service/service.js --server",
"start": "cross-env LOG_LEVEL=error NODE_ENV=production node ./src/service/service.js",
"start::debug": "cross-env LOG_LEVEL=info NODE_ENV=development node ./src/service/service.js",
"start-front-server": "nodemon ./src/express/index.js"
"start-front-server": "nodemon ./src/express/express.js"
},
"repository": {
"type": "git",
Expand All @@ -35,6 +35,7 @@
"chalk": "4.1.0",
"cross-env": "7.0.3",
"express": "4.17.1",
"multer": "1.4.3",
"nanoid": "3.1.20",
"pino": "6.13.0",
"pug": "3.0.0"
Expand Down
17 changes: 16 additions & 1 deletion src/express/api.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

'use strict';

const axios = require(`axios`);
Expand All @@ -9,18 +8,32 @@ const port = process.env.API_PORT || 3000;
const defaultURL = `http://localhost:${port}/api/`;

class API {
// При создании экземпляра данного класса
// передадим базовый URL, на который будем
// добавлять остальные пути
// и время таймаута сервера
constructor(baseURL, timeout) {
this._http = axios.create({
baseURL,
timeout
});
}

// Приватный метод, использующийся в дальнейшем
// По умолчанию делает GET запрос по переданному URL
// В options можно изменить запрос (например, на POST)
// и передать данные
async _load(url, options) {

// делаем запрос по переданному url
const response = await this._http.request({url, ...options});
// Возвращаем результат
return response.data;
}

// Передаём в приватный метод ULR `/offers/`
// По GET - запросу API - сервер вернёт список объявлений
// Аналогичная работа и в других методах
getOffers() {
return this._load(`/offers`);
}
Expand All @@ -45,9 +58,11 @@ class API {
}
}

// Заранее создадим экземляр API и экспортируем его
const defaultAPI = new API(defaultURL, TIMEOUT);

module.exports = {
// А так же экспортируем сам класс
API,
getAPI: () => defaultAPI
};
11 changes: 7 additions & 4 deletions src/express/index.js → src/express/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,28 @@ const mainRoutes = require(`./routes/main-routes`);
const myRoutes = require(`./routes/my-routes`);
const offersRoutes = require(`./routes/offers-routes`);

const {HttpCode} = require(`../constants`);

const DEFAULT_PORT = 8080;

const PUBLIC_DIR = `public`;
const UPLOAD_DIR = `upload`;

const app = express();

app.set(`views`, path.resolve(__dirname, `templates`));
app.set(`view engine`, `pug`);

app.use(express.static(path.resolve(__dirname, PUBLIC_DIR)));
app.use(express.static(path.resolve(__dirname, UPLOAD_DIR)));

app.use(`/`, mainRoutes);
app.use(`/my`, myRoutes);
app.use(`/offers`, offersRoutes);

app.use((req, res) => res.status(404).render(`errors/404`));
app.use((req, res) => res.status(HttpCode.NOT_FOUND).render(`errors/404`));
app.use((err, req, res, _next) => {
console.log(err.message);

res.status(500).render(`errors/500`)
res.status(500).render(`errors/500`);
});

app.listen(DEFAULT_PORT, () => console.log(`Сервер работает на ${DEFAULT_PORT}`));
Loading

0 comments on commit 772b4ac

Please sign in to comment.