node.js form elements array - arrays

How to parse form elements array in NodeJS ?
Like in PHP we get $_POST['answers'] for form elements with names: answers[0], answers[1], answer[2] .... answers[n]

I got my own solution for this, for example I am getting data in var obj:
console.log("\n\n\n\n\n\n\n\n\n");
var obj = {
'answer[\'test\']': 'first',
'answer[\'2\']': 'second'
};
var new_obj = {};
for(key in obj){
key.replace(/([^\[]+)\['([^\]]+)'\]/g, function($0, $1, $2){
new_obj[$1] = new_obj[$1] || {};
new_obj[$1][$2] = obj[key];
})
}
console.log(new_obj);

Check out formidable it can parse any form you give it. It's also the module that connect and express use to parse the form data.

Using the popular node.js framework Express, it is as simple as:
var express = require('express'),
app = express.createServer();
app.use(express.bodyParser());
app.post('/foo', function(req, res, next) {
// Echo the POST body
res.send(req.body);
});
app.listen(3000);
Testing with curl:
curl -d foo=1 -d foo=2 localhost:3000/foo
Similar to in PHP, req.body.foo will be an array with all the foos you posted.
Edit: The querystring module is indeed what Express uses internally. If you need to accept file uploads, use formidable as Jan Jongboom suggests. Otherwise, here's basically how you would do it with just node:
var http = require('http'),
qs = require('querystring');
var app = http.createServer(function(req, res) {
var buffer = '';
req.setEncoding('utf-8');
req.on('data', function(data) {
buffer += data;
});
req.on('end', function() {
var body = qs.parse(buffer);
});
});

Related

Admin on Rest Mongoose compatible queries

I am using Admin on Rest to create a dashboard for my rest calls.
The call is going through and I looked at the call in my console.
GET /api/v2/admin/user?_end=10&_order=DESC&_sort=id&_start=0 200 61.102 ms - 2846
But it isn't returning anything, which I assume is because Mongo doesn't take in queries with _end, _order, _start, as well as it uses _id instead of id.
What would be the best workaround for this? As I can't modify the call going in.
The logic for the endpoint is below. I am also (not pictured) trying to manually create the sorting options but I feel like that isn't efficient.
// routes/admin/user.js
var express = require('express'),
router = express.Router();
var User = require(__models + 'user');
router.route('/')
.get(function(req, res, next){
var query = req.query || {};
User.find(query).then(users => {
return res.json(users);
}).catch(err => next(err));
});
module.exports = router;
You need to write your own REST Client for creating queries in formats your REST API understands.
https://marmelab.com/admin-on-rest/RestClients.html#writing-your-own-rest-client
I created a util function to do this for me.
module.exports.getJsonFromUrl = function(query) {
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
};
And I called it from controller like so
var query = routeUtil.getJsonFromUrl(req._parsedUrl.query);

How to post JSON object angularjs

I would like post object and read it on node server but I have an error.
controller :
$scope.update = function(contact) {
console.log(contact);
$http.post('/contactlist/' + contact).then(function(response) {
console.log(response);
});
};
server node :
app.post('/contactlist/:contact', function (req, res, next) {
console.log(req.body);
res.json();
});
server node head:
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var connection = *****************
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname + "/public"));
Screenshot of the error network POST :
enter image description here
server error of console.log(req.body);
[object Object]
SyntaxError: Unexpected token o in JSON at position 1
You are not passing any parameter in your post API. POST needs a parameter to be passed and since you are passing the parameter in the request URL, you can try by passing an empty object like this:
$http.post('/contactlist/' + contact,{}).then(function(response) {
console.log(response);
});
You are trying to concatenate an object in the URL which is not a good approach. If you want to still do this way, stringify it and then append it to URL. And you can get it with the help of req.query. But it is better if you change the url and pass contact as a parameter to your API call.
Problem solved by :
var OBJ = JSON.stringify(yourOBJ);
For node js there different syntax please see below:
var yourObj = {};
$http.post('/contactlist/' + contact, {data: yourObj}).then(function(response)
{
console.log(response);
});
This will work

MongoDB does not refresh data automatically?

I use MEAN stack for developing. And after adding some data to MongoDB, the new data is available in front-end only after restarting NodeJS server. There is any way to update MongoDB data 'online'?
This is my API (Node.js):
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
mongoose.connect('mongodb://localhost/vt');
var Video = mongoose.Schema({
idv: String,
thumbnail: Number,
aud : String,
title : String,
description : String
});
var db;
var video = mongoose.model('video',Video);
video.find({}, function (err, data) {
db = data;
});
router.get('/api/videos', function (req, res) {
res.send(db);
});
module.exports = router;
I am adding data via Mongo Shell, it looks like this: db.videos.insert({'idv': '8ifJvMlITNc'}). After that, I get all data from videos table via Ajax. There is no new data in the response from the server until I restart Node.js server
In your Node.js app you are fetching the data only once. You are not fetching it when request is received. Change the code to following and you don't have to restart for reading data:
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
mongoose.connect('mongodb://localhost/vt');
var Video = mongoose.Schema({
idv: String,
thumbnail: Number,
aud : String,
title : String,
description : String
});
var video = mongoose.model('video',Video);
router.get('/api/videos', function (req, res) {
video.findOne({}, function (err, data) {
if (err || !data) {
res.status(500).send();
}
res.status(200).send(data);
});
});
module.exports = router;
Hope this helps.

POST returns 404 Not Found

I've recently started using MEAN Stack to create a basic application, so im a total beginner, I set up my controllers and everything and I want to post, however it returns api/user not found, can someone pinpoint the problem and help me out? Thanks.
Server.js:
var app = require ('./app/app');
var signupController = require ('./server/signup-controller');
app.post('api/users', signupController.create);
app.listen('8080', function(){
console.log('[OK] => HTTP Server listening on http://localhost:8080');
require('./app/db').init('mongodb://localhost:27017/shopialmedia' );
});
Server side Controller (signup-controller.js):
module.exports.create = function (req, res) {
console.log(req.body);
}
Client Side Controller (signup-controller.js):
app.controller('signupController', ['$scope', '$resource', function ($scope, $resource) {
var User = $resource('/api/users');
$scope.createUser = function () {
var user = new User();
user.email = $scope.userEmail;
user.password = $scope.userPass;
user.firstName = $scope.userFName;
user.lastName = $scope.userLName;
user.age = $scope.userAge;
user.$save(function (result){
$scope.user.push(result);
$scope.userEmail = '';
$scope.userPass = '';
$scope.userFName = '';
$scope.userLName = '';
$scope.userAge = '';
});
}
}]);
My module :
var app = angular.module('signupApp', ['ngResource']);
My app.js :
var express = require ('express');
var app = express();
app.use(express.static('public'));
require('./routes')(app);
module.exports = app;
When I go to run the application on my web page and submit the information, it returns api/user 404 Not found any suggestions on what to do, I'd greatly appreciate it. As I said im a beginner so please take that into consideration.
Server.js Add:
app.get('api/users', signupController.list);
signup-controller.js Add:
mongoose = require('mongoose'),
User = mongoose.model('User');
module.exports.list = function(req, res){
var searcher = req.query || {};
User.find(searcher)
.sort('-created')
.exec(function (err, users) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
res.json(users);
});
};
Obviously, you'll also have to connect to mongoose with a file probably called main.js then you'll need a UserModel.js (or equivalent) where you can define the attributes of your user etc using the mongoose Schema...
I mean you're missing a lot if you want something a little simpler to start you can just do:
module.exports.list = function(req, res){
var users = [];
res.json(users);
};
Also think you need this and this is also nicer formatting:
var router = express.Router();
router.route('/')
.get(users.list)
.get(users.create)
app.use('/api/users', router);
Not sure what this is supposed to do or what ./routes is: require('./routes')(app);

How to create RestFull api with express and node.js?

I am very new to node and express i read some documentation but i did not get any solid understanding how to create rest api with node, So with below basic code i just want to create get api with express and return response to angularjs factory method.I would like to get help and better understanding for the following .
1- How to return response with GET api ?
2- If we have json object how can i pass that data using GET api ?
app.js
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static('./'));
var server = app.listen(3000, function(){
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http',host,port);
});
app.get('/test', function(req, res) {
res.type('text/plain'); // set content-type
res.send('i am a beautiful butterfly'); // send text response
});
workerController.js
$scope.getTestData = function(){
alert('got function working');
workerFactory.getData().then(function(response){
var dataResponse = response.data;
console.log(dataResponse);
})
}
workerFactory.js
angular.module('myApp').factory('workerFactory', function ($http) {
'use strict';
return {
getData: function(){
return $http.get('/test');
}
}
});
For the second part, how to pass a JSON object back. You can change your API code to something like:
app.get('/test', function(req, res) {
res.json({message: 'i am a beautiful butterfly'}); // send a JSON response
});
I'm just working on the first part of the question
You can get a full working REST-full API code by using Amplication, it's an open-source for generating Node.js code by only defining your data model.
As you have the basic understanding on REST API you can use this node module
https://github.com/swagger-api/swagger-node for creating great REST API.

Resources