Handle post request html

NodeJS handling POST requests.

In the last article I talked about the client server model and how data can be sent from client to server and back to client with the use of GET requests. Although GET requests power the internet (you made a get request just to view this article), Sometimes a client might want to send extra information to the server (you’ve done this for usernames and passwords or adding something to a database). For example in an html form or URL query. We’ll explore this through the use of POST requests.

For the reader

In this article I want to delve more into how a client can send more data to a server. This is called a POST request. A POST request is where extra data can be sent to a server where it can be parsed and used by the backend. I will be using NodeJS (other programming languages also offer the use of http requests, and http body parsing with post requests). This article assumes that you know nothing about POST requests and you can follow along step by step through this article.

How do POST requests work?

A POST request is a request method that is supported by HTTP protocol. This type of request encloses data in the HTTP request body. In contrast a GET request does not enclose data in the HTTP request body, and is primarily used to request a certain resource from a server (for example getting a page for Wikipedia). POST requests are often used in conjunction with databases to store data into a database, authentication to authenticate a username and password, or any other task where there has to be more data than just a URL path.

Lets start by making sure NPM is installed.

Image description

First make sure that NodeJS is installed on your machine (this can be different for Linux, mac, and window machines. See NodeJS documentation for more). To do this lets check with the command node -v

You should receive your current NodeJS version as an output (for example I’m currently using version 8.11.0). If you do not receive an output like this refer to the NPM documentation.

Читайте также:  Shrink image in html

Now lets create our directory and install the required modules.

Image description

Now lets create our directory to that’ll hold all our files and dependencies. Next use npm install express body-parser . Express is our backend framework that handles HTTP requests (this was covered in the last article) and body-parser is an NPM module that handles POST request data. Your terminal should look something like this.

Lets create the HTML page with the form that we’ll be making a POST request with.

For this I will create another file called index.html (in the real world you probably would have this file in a static, routes, or pages directory I’m just adding it into the root directory for this example.). Also the text in the HTML file should look like this and should include our input fields, and our submit button.
Image description
And your root directory should now look like this.
Image description

Now lets move onto the backend we’ll start with handling the homepage GET request.

Finally now we can create the logic that takes in the POST request data, but first we need to handle serving our homepage. For this lets create a server.js file in the root directory. This file will house our backend logic for the form and return something, along with a get request for our homepage and path parameters. Lets create a server.js file (commonly called an app.js file) and have it return a homepage, then we can add more code to it and have it work with post requests. The server.js file should look like this.
Image description
So far our server.js file (our express file) can handle a GET request to a / URL parameter, returning our homepage. We can check this by running node server.js from the terminal and then going to our web browser (in my case I’m using google chrome) and going to localhost:8080 you should see the HTML file you created earlier and it should look like this.Image description

Now lets add the logic for our POST request.

Now lets add our POST request logic to our server.js file. Remember that body-parser module we downloaded using NPM? Well that’s what we’ll be using here to handle our POST request form data. First you’ll import the body-parser module (like how we did with express), then make sure out body-parser variable uses json to handle data. Then add another app method to handle everything. All in all it should look like this. Also make sure to read the picture here to see a more descriptive example of how everything works.
Image description
Now run the server.js file using node server.js and type into the index.html (at localhost:8080) form. your data and your server.js should receive the incoming request and work with it! All in all it should look like this. Notice that our server.js file has console.log’d our incoming data!
Image description

Читайте также:  Найти два максимальных элемента массива python

You’ve officially handled POST request data!

You did it! You’ve handled a POST request using Express and body-parser! Now you can accept form data from any HTML form, and do something with it. Like adding something to a database, doing something with the data, authentication, or letting the user know that there form was sent! Also you can explore things like Fetch, or Axios to get even more of a handle on POST requests.

Thank you for reading!

Thanks for reading. I hope you found this article enjoyable and learned something in the process. If there’s something that you feel like I’ve left out then comment down below, or message me directly. Also leave a follow if you found this article informative! 🙂

What I’m up to lately.

My names David and I’ve been working on software web development for about 2 years now. Mostly free lance work. I know Python, JavaScript, Bash, CSS, HTML, PostgreSQL, MongoDB, and many other technologies. If you want to get in touch check me out here at davidesquerra.com. At this website you can text me directly or email me. And like I said above thanks for reading :).

Источник

Отправка данных формы

Сама форма обычно предназначена для получения от пользователя информации для дальнейшей пересылки её на сервер, где данные формы принимает программа-обработчик. Такая программа может быть написана на любом серверном языке программирования вроде PHP, Perl и др. Адрес программы указывается в атрибуте action тега , как показано в примере 1.

Пример 1. Отправка данных формы

В этом примере данные формы, обозначенные атрибутом name ( login и password ), будут переданы в файл по адресу /example/handler.php. Если атрибут action не указывать, то передача происходит на адрес текущей страницы.

Передача на сервер происходит двумя разными методами: GET и POST, для задания метода в теге используется атрибут method , а его значениями выступают ключевые слова get и post . Если атрибут method не задан, то по умолчанию данные отправляются на сервер методом GET. В табл. 1 показаны различия между этими методами.

Табл. 1. Различия между методами GET и POST

GET POST
Ограничение на объём4 КбОграничения задаются сервером.
Передаваемые данныеВидны сразу всем.Видны только при просмотре через расширения браузера или другими методами.
КэшированиеСтраницы с разными запросами считаются различными, их можно кэшировать как отдельные документы.Страница всегда одна.
ЗакладкиСтраницу с запросом можно добавить в закладки браузера и обратиться к ней позже.Страницы с разными запросами имеют один адрес, запрос повторить нельзя.

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

Уникальное сочетание параметров в адресной строке однозначно идентифицирует страницу, так что страницы с адресами ?q=node/add и ?q=node считаются разными. Эту особенность используют системы управления контентом (CMS, Content management system) для создания множества страниц сайта. В реальности же используется один файл, который получает запрос GET и согласно ему формирует содержимое документа.

Ниже перечислены типовые области применения этих методов на сайтах.

GET

Передача небольших текстовых данных на сервер; поиск по сайту.

Поисковые системы, формы поиска по сайту всегда отправляются методом GET, это позволяет делиться результатами поиска с друзьями, слать ссылку по почте или выкладывать её на форуме.

POST

Пересылка файлов (фотографий, архивов, программ и др.); отправка комментариев; добавление и редактирование сообщений на форуме, блоге.

Работа с формой по умолчанию происходит в текущей вкладке браузера, при этом допустимо при отправке формы изменить этот параметр и открывать обработчик формы в новой вкладке или во фрейме. Такое поведение задаётся через «имя контекста», которое выступает значением атрибута target тега . Популярные значения это _blank для открытия формы в новом окне или вкладке, и имя фрейма, которое задаётся атрибутом name тега (пример 2).

Пример 2. Открытие формы во фрейме

В данном примере при нажатии на кнопку «Отправить» результат отправки формы открывается во фрейме с именем area .

Элементы формы традиционно располагаются внутри тега , тем самым определяя те данные, которые будут передаваться на сервер. В то же время в HTML5 есть возможность отделить форму от её элементов. Это сделано для удобства и универсальности, так, сложный макет может содержать несколько форм, которые не должны пересекаться меж собой или к примеру, некоторые элементы выводятся с помощью скриптов в одном месте страницы, а сама форма находится в другом. Связь между формой и её элементами происходит в таком случае через идентификатор формы, а к элементам следует добавить атрибут form со значением, равным этому идентификатору (пример 3).

Пример 3. Связывание формы с полями

В этом примере тег однозначно отождествляется через идентификатор auth , а к полям, которые следует отправить с помощью формы, добавляется form=»auth» . При этом поведение элементов не меняется, при нажатии на кнопку логин и пароль пересылаются на обработчик handler.php.

Хотя параметры передачи формы традиционно указываются в теге , их можно перенести и в кнопки отправки формы ( и ). Для этого применяется набор атрибутов formaction , formmethod , formenctype и formtarget , которые являются аналогами соответствующих атрибутов без приставки form. В примере 4 показано использование этих атрибутов.

Все новые атрибуты форм не поддерживаются некоторыми браузерами, в частности, Internet Explorer и Safari.

Источник

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