Last active
July 13, 2017 19:35
-
-
Save andrIvash/9b6a46ca605988277cf461f0e0685b1e to your computer and use it in GitHub Desktop.
Node Send form example with bodyParser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ajax.js ---------------------------- сторона клиента | |
| function get(url, data) { | |
| return new Promise(function(resolve, reject) { | |
| var req = new XMLHttpRequest(); | |
| req.open('POST', url); | |
| req.setRequestHeader('content-type', 'application/json'); // очень важно укзать заголовок !!! | |
| req.onload = function() { | |
| if (req.status == 200) { | |
| resolve(req.response); // в случае успеха получаем ответ сервера | |
| } | |
| else { | |
| reject(Error(req.statusText)); | |
| } | |
| }; | |
| req.onerror = function() { | |
| reject(Error("Network Error")); | |
| }; | |
| req.send(JSON.stringify({"name": data})); // формируем итоговый обьект для отсылки | |
| }); | |
| } | |
| // Use it! - пример отправки данных | |
| var form = document.getElementById('form'); | |
| form.addEventListener('submit', function(evt){ | |
| var name = form.elements.name.value; | |
| evt.preventDefault(); | |
| var url = '/users'; | |
| get(url, 'my name is John').then(function(response) { | |
| console.log("Success!", response); | |
| }, function(error) { | |
| console.error("Failed!", error); | |
| }); | |
| }); | |
| // app.js ---------------------------- сторона сервера | |
| var express = require('express'); | |
| var router = express.Router(); | |
| /* POST listing. */ | |
| router.post('/', function(req, res, next) { | |
| var result = {status: 'ok', data: req.body}; | |
| res.send(result); | |
| }); | |
| module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment