Javascript backend node js

7 best Node.js frameworks to build backend APIs in 2023

Node.js helps us build fast and high-performance backends for websites and mobile apps of all sizes. This job is made easier and more convenient thanks to the help of open-source frameworks.

In this article, we will walk through a list of the best Node.js frameworks for building APIs in 2023 (RESTful and GraphQL).

Express

  • GitHub stars: 59.6k+
  • NPM weekly downloads: 28m – 35m
  • Written in: pure Javascript
  • License: MIT
  • Links: Official website | GitHub repo | NPM page

Express is one of the oldest, most stable Node.js frameworks. It first debuted in 2010, which was shortly after the arrival of Node.js.

Express is lightweight, minimal, and flexible. It provides a thin layer of fundamental web application features, a myriad of HTTP utility methods, and middleware for quickly creating REST API. You can also easily implement GraphQL by using the express-graphql library.

A minimal Express API that runs on port 3000:

const express = require('express') const app = express() app.get('/', (req, res) => < res.send('Hello World') >) app.listen(3000)

Fastify

  • GitHub stars: 26k+
  • NPM weekly downloads: 700k – 1m
  • Written in: Javascript and Typescript
  • License: MIT
  • Links: Official website | GitHub repo | NPM page

Fastify, as its name suggests, is a framework that focuses on performance and speed as well as saving resources for the server when it is up and running.

Like Express, Fastify is quite lightweight, highly flexible, and fully extensible via its hooks, plugins, and decorators. As far as we know, this is one of the fastest web frameworks these days, with the ability to serve up to 76+ thousands of requests per second.

import Fastify from 'fastify' const fastify = Fastify(< logger: true >) fastify.get('/', async (request, reply) => < reply.type('application/json').code(200) return < hello: 'world' >>) fastify.listen(< port: 3000 >, (err, address) => < if (err) throw err >)

NestJS

  • GitHub stars: 53.5k+
  • NPM weekly downloads: 1.5m – 2m
  • Written in: Typescript
  • License: MIT
  • Links: Official website | GitHub repo | NPM page

Nest is a progressive, modern Node.js framework that is growing rapidly, and more and more large businesses are choosing it for their projects.

Nest aims to provide an application architecture out of the box which allows for the effortless creation of highly testable, scalable, loosely coupled, and easily maintainable applications. The architecture is heavily inspired by Angular.

Defining REST API with Nest is simple. If you want to implement GraphQL, just use the built-in @nestjs/graphql module.

Koa

  • GitHub stars: 33.5k+
  • NPM weekly downloads: 1.1m – 1.5m
  • Written in: pure Javascript
  • License: MIT
  • Links: Official website | GitHub repo | NPM page

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.

Читайте также:  Python проверка регистра символа

By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error handling. Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable.

Connect

  • GitHub stars: 9.6k+
  • NPM weekly downloads: 5m – 6m
  • Written in: Javascript
  • License: MIT
  • Links: GitHub repo | NPM page

Connect is a lightweight HTTP server framework for Node.js whose unpacked size is only around 95 kB. It is simple and glues with various middleware to handle incoming requests. There are a very rich number of plugins to extend Connect’s behaviors, such as:

You can install connect and some plugins by running:

npm i connect compression cookie-session body-parser

And use them together like this:

const connect = require('connect'); const http = require('http'); const app = connect(); // gzip outgoing response const compression = require('compression'); app.use(compression()); // session stuff const cookieSession = require('cookie-session'); app.use(cookieSession(< keys: ['kitty', 'puppy'] >)); // using body-parser var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded()); // respond to all requests app.use(function(req, res)< res.end('Hello from Connect!\n'); >); // Listen to incoming requests on port 3000 http.createServer(app).listen(3000);

LoopBack

  • GitHub stars: 4.4k+ (the previous version gained 13.5k)
  • NPM weekly downloads: 26k – 40k
  • Written in: Javascript and Typescript
  • License: MIT
  • Links: Official website | GitHub repo | NPM page

LoopBack is a highly extensible Node.js and TypeScript framework
for building APIs and microservices.

LoopBack 4 is the latest version of this awesome framework. It comes with a new, improved programming model with Dependency Injection and new concepts such as Components, Mixins, Repositories, etc., making this the most extensible version yet.

If you want to translate from REST to GraphQL with LoopBack, the official recommended approach in the docs is to install OpenAPI-to-GraphQL:

npm i -g openapi-to-graphql-cli

AdonisJS

  • GitHub stars: 13.4k (Adonis core)
  • NPM weekly downloads: 8k – 15k
  • Written in: Typescript
  • License: MIT
  • Links: Official website | GitHub repo | NPM page

Adonis is a Node.js framework that focuses on developer ergonomics, stability, and confidence. It takes care of much of the web development hassles, offering you a clean and stable API to build Web apps and microservices.

Conclusion

We have come across the best Node.js frameworks for building APIs in 2023. You don’t have to understand all of these, but knowing that they exist and knowing their characteristics will help you to have more approaches and strategies when building and developing the Node.js backend for new projects.

If you would like to explore more interesting things related to Node.js, take a look at the following articles:

You can also check out our Node.js category page for the latest tutorials and examples.

Источник

Как запустить бэкэнд на Node JS

В этой статье напишем простой бэкэнд на NodeJS. Этот сервер будет полезен для разработки веб-приложений.

Необходимые условия

  • NodeJS и npm. Их можно скачать с официального сайта nodejs.org. npm установится автоматически вместе с NodeJS.
  • Предпочитаемый IDE, например, Visual Studio Code.
  • Опционально, установить git для удобной работы с кодом.

О приложении

В этой статье напишем небольшой REST API сервер, который будет отдавать список дел по GET запросу. Структура папок будет выглядеть следующим образом.

Создание бэкэнда на NodeJS

Эта команда создаст файл package.json . Ключ -y заполнит все поля в package.json значениями по умолчанию. Файл package.json содержит информацию о проекте — название, версия, описание, список зависимостей, скрипты для запуска, сборки и тестирования. Все поля можно будет изменить и вручную после его создания. После инициализации package.json будет выглядеть следующим образом.

< "name": "my-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": < "test": "echo \"Error: no test specified\" && exit 1" >, "keywords": [], "author": "", "license": "ISC" >

Создадим файл index.js . В нем будет находится код для запуска сервера. Если порт не задан в переменных среды, то будет использован порт 3010 .

// my-app/index.js const express = require('express'); const PORT = process.env.PORT || 3010; const app = express(); app.use((req, res, next) => < res.setHeader('Access-Control-Allow-Origin', '*'); next(); >); app.listen(PORT, () => < console.log(`Server listening on $`); >);

Запуск сервера

В поле scripts файла my-app/package.json добавим команду для запуска сервера. В результате сможем запускать наш сервер с помощью команды npm start .

Из папки my-app/ запустим команду npm start . Если ошибок нет, получим сообщение, что сервер прослушивает порт 3010.

PS C:\tutorials-coding\nodejs-backend\my-app> npm start > my-app@1.0.0 start > node ./index.js Server listening on 3010

Создание API

API это интерфейс, с помощью которого приложение будет общаться с веб-сервером, т.е. запрашивать, изменять или удалять данные. Мы сможем получать эти данные, например, в веб-приложении на React. О том как, делать API запросы к серверу из React приложения, можно прочитать в этой статье. В нашем случае мы создадим API для получения списка дел в формате JSON. Создадим файл /my-app/todo-items.json c объектами todo. Этот массив будем отдавать по запросу /api/todo-items .

Далее добавим код для создания эндпоинта /api/todo-items . Веб-приложение сможет отправлять на него GET запрос.

// my-app/index.js // . const todoItems = require('./todo-items.json'); app.get('/api/todo-items', (req, res) => < res.json(< data: todoItems >); >); app.listen(PORT, () => < console.log(`Server listening on $`); >);

Ответ от Node JS сервера

Для того чтобы изменения применились нужно перезапустить NodeJS сервер. Для остановки скрипта в терминале, в котором запущен npm start , нужно нажать Ctrl + C ( Command + C ). Далее снова запускаем npm start . Для проверки эндпоинта, вставим в адресную строку браузера http://localhost:3010/api/todo-items . В результате получим такой ответ.

Отправка HTTP запроса к серверу

К этому моменту у нас уже есть рабочий сервер, который умеет принимать запросы и отдавать данные. Для проверки работы сервера вне веб-приложения можно воспользоваться такими программами как Postman или Insomnia.

Автоматический перезапуск сервера после обновления кода

Ранее для того чтобы изменения исходного кода сервера вступили в силу, мы перезапускали сервер. Можно ускорить процесс разработки и автоматизировать эту часть с помощью инструмента nodemon. nodemon будет следить за файлами в каталоге, в котором был запущен nodemon, и если какие-либо файлы изменятся, он автоматически перезапустит ваше node js приложение. Установим nodemon как зависимость для разработки.

npm install --save-dev nodemon

Добавим новый скрипт dev в my-app/package.json .

Далее запустим сервер следующим образом.

Теперь, после изменений в коде, увидим, что сервер перезапускается сам. Исходный код

Как загружать файлы в React с помощью NodeJS и Express

В этой статье рассмотрим как загрузить файлы в React использованием Express в качестве бэкенда.

Создание бэкенда на Express

Во-первых, мы создаем POST API с использованием NodeJS и Express, который поможет нам загружать файлы (изображения, pdf и т. д.) на внутренний сервер.

Настройка серверного проекта

mkdir fileupload cd fileupload npm init -y

Установка пакетов

Теперь нам нужно установить четыре пакета: express , express-fileupload , cors и nodemon . Выполните приведенную ниже команду, чтобы установить пакеты.

npm i express express-fileupload cors nodemon

Теперь откройте папку fileupload в вашем любимом редакторе кода и создайте новый файл с именем server.js . Добавьте следующий код в файл server.js .

// server.js const express = require('express'); const fileUpload = require('express-fileupload'); const cors = require('cors') const app = express(); // middleware app.use(express.static('public')); // для доступа к файлам в папке public app.use(cors()); app.use(fileUpload()); // API для загрузки файлов app.post('/upload', (req, res) => < if (!req.files) < return res.status(500).send(< msg: "file is not found" >) > const myFile = req.files.file; // метод mv() помещает файл в папку public myFile.mv(`$/public/$`, function (err) < if (err) < console.log(err) return res.status(500).send(< msg: "Error occurred" >); > // возвращаем ответ с именем файла и его расположением return res.send(); >); >) app.listen(4500, () => < console.log('server is running at port 4500'); >)

В приведенном выше коде мы сначала импортировали три пакета: express , express-fileupload и cors , а затем создали приложение express вызвав функцию express() Наш маршрут POST API - /upload . Мы помещаем файлы в общую папку public . Для этого нам нужно создать папку public внутри нашего бэкенд-проекта.

Добавление скриптов

Чтобы запускать и перезапускать сервер мы используем nodemon . Откройте файл package.json и добавьте следующий код в scripts .

Теперь запустите сервер, выполнив команду npm run server в терминале.

Создание приложения React

npx create-react-app react-fileupload

Теперь измените текущий рабочий каталог, выполнив приведенную ниже команду.

Установка библиотеки Axios

Нам также необходимо установить клиентскую библиотеку axios , которая используется для выполнения http-запросов.

Создание компонента загрузки файлов

Откройте папку react-fileupload в своем любимом редакторе кода и создайте новый файл с именем fileupload.js внутри папки src . Теперь добавьте следующий код.

// fileupload.js import React, < useRef, useState >from 'react'; import axios from 'axios'; function FileUpload() < // для хранения загруженного файла const [file, setFile] = useState(''); // для хранения ответа от бекенда const [data, getFile] = useState(< name: "", path: "" >); const [progress, setProgess] = useState(0); // progessbar const el = useRef(); // для доступа к инпуту const handleChange = (e) => < setProgess(0) const file = e.target.files[0]; // доступ к файлу console.log(file); setFile(file); // сохранение файла >const uploadFile = () => < const formData = new FormData(); formData.append('file', file); // добавление файла axios.post('http://localhost:4500/upload', formData, < onUploadProgress: (ProgressEvent) => < let progress = Math.round( ProgressEvent.loaded / ProgressEvent.total * 100 ) + '%'; setProgess(progress); >>).then(res => < console.log(res); getFile(< name: res.data.name, path: 'http://localhost:4500' + res.data.path >) >).catch(err => console.log(err)) > return ( 
onChange= />
>>
alt= />>
); > export default FileUpload;

В приведенном выше коде мы использовали хуки react для управления состоянием, и у нас есть две функции: handleChange и uploadFile . handleChange вызывается после того, как пользователь выбрал файл. Функция uploadFile() используется для загрузки файла в наш /upload api. Существует также индикатор выполнения, который показывает прогресс загрузки файла на сервер, а также мы отображаем изображение после получения ответа от сервера.

Добавление стилей css

.App < margin: 2rem auto; max-width: 800px; >img < width: 500px; height: 500px; object-fit: contain; >.progessBar < height: 1rem; width: 0%; background-color: rgb(68, 212, 231); color: white; padding:2px >.file-upload < box-shadow: 2px 2px 2px 2px #ccc; padding: 2rem; display: flex; flex-direction: column; justify-content: space-between; font-size: 1rem; >input , div , button < margin-top: 2rem; >.upbutton

Теперь импортируйте компонент FileUpload в файл App.js .

// App.js import React from 'react'; import FileUpload from './fileupload'; import './App.css'; function App() < return (  
); > export default App;

Запустите приложение React, запустив npm start .

Источник

Оцените статью