I'm having problem with sending data from ajax client to nodejs and storing that data in a collection in mongodb.
Here's my client code:
testdata = {'test1':'test1', 'test2':'test2'}
for(i=0;i<2;i++){ // for testing purposes
$(".btn").click(function(){
$.ajax({
url: 'http://localhost:8000/1',
type: 'post',
dataType: 'json',
data: testdata ,
success: function(){
console.log(i);
}
});
});
}
And my node.js server post handler with express:
app.post('/1', function(req, res){
db.collection('test', function(err, collection){
var data = req.body;
collection.insert(data, function (err, result) {
if(!err){
console.log(result);
}else{
res.end();
}
});
});
});
Body parser middleware is on, mongo is on of course, but my test collection is not receiving any data. I have a sence that i'm missing something very obvious here. Thanks for the help, much appreciated.
Related
I have a Nodejs and d3.js programs which handle json data, send it via cross-domain and save a file. I have two JSON array which are: nodes and links. I need to save these into a file in another domain. In front-end side I am preparing http message like this,
function sendLinks()
{
jQuery(document).ready(function($)
{
$.ajax({
type:'POST',
url: 'http://192.168.80.143:2800/',
data:JSON.stringify(links),
contentType: "application/json; charset=utf-8",
dataType: 'json',
processData: false,
error: function(data)
{
console.log("error", data);
},
success: function(data)
{
console.log("success", data);
}
});
});
}
In the server side, I have the following code(nodejs)
app.use(function(req, res) {
//write a file
fs.writeFile('links.json', JSON.stringify(req.body), function(err) {
if(err) return console.log(err);
console.log('File created > links.json');
});
res.setHeader('Content-Type', 'application/json');
res.write('Message taken: \n');
res.end(req.body);
res.send("OK");
});
I want to do that for nodes JSON array in a different file name(e.g. nodes.json). How can I do that? Can I handle with the same http message?
Thanks,
Just return data: JSON.stringify({ links: links, nodes: nodes }), and unpack appropriately at serverside.
I am using Node.js with Express and MongoDB.
I have a page, '/score' that calculates the user's score from a quiz taken on the previous page. The '/score' route is below:
app.get('/score', stormpath.getUser, function(req, res) {
var quiz = req.session.mostRecentQuiz;
db.collection('quizzes').find(quiz).toArray(function (err, docs) {
assert.equal(err, null);
var quiz;
docs.forEach(function (doc) {
quiz = doc.quiz;
});
res.render('score', {quiz: quiz});
});
db.collection('users').update({user: req.user.username}, { $set: {"mostRecentQuiz": quiz } }, function (err, result) {
if (err) throw err;
console.log(result);
} );
});
After getting the quiz answers from the DB, I use some client-side JavaScript on the /score page to calculate the user's score and then report it to the user. However, I would like to get that same score back to my MongoDB, but I am not sure how best to accomplish that.
Can I use AJAX to accomplish this, or would it be better to redirect to a new page?
If you're already using Express, the simplest way would be to define a route for updating the score. Then you can send the data to the server via AJAX.
In order to parse the request parameters install the body-parser module.
Server:
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.put('/score', stormpath.getUser, function (req, res) {
console.log(req.body); // there should be your received data
// save it to the database
db.collection('yourcollection').updateOne(
{}, // your query for updating the data in the wished field
function(err, results) {
if(err) { return res.json(err); };
return res.json(results);
});
});
Client - if you're using jQuery:
$.ajax({
url: '/score',
type: 'PUT',
contentType: 'application/json',
data: {'score':1000}, // put here your data to send it to the server
success: function(data){
console.log(data);
}
});
Some documentation:
MongoDB update: https://docs.mongodb.com/getting-started/node/update/
jQuery AJAX: https://api.jquery.com/jquery.ajax/
My client side
$.post("http://localhost:3000/scrape",
{
data: 'something'
},
function(data, status){
console.log(data);
});
What I do in node.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/scrape', function (req, res) {
console.log(req.body.data)
});
But I got undefined in console.log(req.body.data), any idea why?
Your data must be of json format. since you are using bodyParser.json().
Try setting the http header, Content-type as application/json in your $.post call and send a valid json structure as data
$.ajax({
url: "scrape",
type: "POST",
data: JSON.stringify({ someData : "someData}),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
console.log(data)
},
error: function(){
console.log('error in sending request')
}
})
console.log(req.body.data)
returns undefined because the data is in req.body you should console.log(req.body)
and add app.use(bodyParser.urlencoded({extended: false})); so that data not in json format can also be parsed.
if you want req.body.data have data then make request like
$.post("http://localhost:3000/scrape",
{
data: {data: 'something'}
},
function(data, status){
console.log(data);
});
also your request is not sending any response you need to do something like
app.post('/scrape', function (req, res) {
console.log(req.body.data)
res.status(200).json({data: reqr.body.data});
});
hope it helps :)
I'm trying to implement functionality which takes data from form inputs on the client-side and sends it to the server to be processed by my Nodejs backend.
I've got the server-side function working, but I'm unsure as to how I would go about sending the data from the client-side form to my backend server via the $.ajax GET request that submits the form.
The code I have so far:
Server side function:
app.get('/id', function(req,res) {
var query = "SELECT * FROM Control";
connection.query(query, function() {
console.log(query);
});
});
Client side function:
function select()
{
$.ajax({
type: 'get',
url: '/id',
success: function(data) {
var ceva = data;
console.log('#ceva');
},
error: function(err) {
console.log(err);
}
});
}
You want to use a POST request rather than a GET request. Doing so will allow you to send data along with the request that you can then use in your query on the server side and send the response back to your client. Like so:
Client Side
function select() {
var id = $('#My-ID-Input').val();
$.ajax({
type: 'post',
url: '/id',
data : {
id : id
},
success: function(data) {
var id = data.id;
$('#My-ID-Input').val(id);
},
error: function(err) {
console.log(err);
}
});
}
Server Side
app.post('/id', function(req, res) {
var data = req.body;
var id = data.id;
var query = "SELECT * FROM Control WHERE id=" + id;
connection.query(query, function(error, result) {
console.log(result);
res.send(result);
});
});
GOTCHA!
You need to make sure that you have the express bodyparser
middleware implemented into your server to ensure that the data sent
as the body of the post request is then parsed into an object literal
on the server side. In your server module/file, you'll need to include the following code, and ensure that you've npm install body-parser:
var bodyParser = require('body-parser');
app.use( bodyParser.json() );
This is to start with a very basic page: HTML Form, a button, and a div-box.
.click of the button would POST the Form data through AJAX.
The data is to be stored in MongoDB, and retrieved into the div-box without a page-refresh.
AJAX from index.html:
$(document).ready(function()
{
// handle button clicks
$('#buttonID').click(function() {
// make an ajax call
$.ajax({
dataType: 'jsonp',
jsonpCallback: '_wrapper',
data: $('#formID').serialize(),
type: 'POST',
url: "http://localhost:9999/start",
success: handleButtonResponse,
});
});
function handleButtonResponse(data)
{
// parse the json string
var jsonObject = JSON.parse(data);
$('#reponseID').append( jsonObject.message );
}
});
app.js:
var express = require('express'),
app = express();
cons = require('consolidate');
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + "/views");
var mongoclient = new MongoClient(new Server('localhost', 27017,
{ 'native_parser' : true }));
var db = mongoclient.db('database_name');
app.get('/', function (req, res) {
db.collection('collectionName').find({}, function (err, doc) {
res.render('index', doc);
});
response.writeHead(200, {"Content-Type:": "application/json"});
var submittedPost = {};
submittedPost['message'] = 'Proof that Node and Mongo are working..';
response.write( "_wrapper('" );
response.write( JSON.stringify(submittedPost) );
response.write( "')");
response.end();
});
app.get('*', function (req, res) {
res.send("404..", 404);
});
mongoclient.open(function (err, mongoclient) {
if (err) throw err
app.listen(9999);
console.log("Express server started on port 9999");
});
How/Where does the JSON connect to/from MongoDB?
Also, does Express require a templating engine, such as Consolidate? If so, how/where does that fit in?
Few suggestions
Regarding the ajax call in index.html
If your index.html is served by the same server, then please don't use a cross domain call. The url property in $.ajax could be a relative url like /start.
Also you can think of not using jsonp request.
the call could be like
$.ajax({
dataType: 'json',
data: $('#formID').serialize(),
type: 'POST',
url: "./start",
success: handleButtonResponse,
});
How/Where does the JSON connect to/from MongoDB?
In you ajax call you are requesting for ./start, So the same route should be made in your express server. like
app.get('/start', function (req, res) {
db.collection('collectionName').insert({req.data}, function (err, doc) {
//rest of code
});
});
does Express require a templating engine, such as Consolidate? If so, how/where does that fit in?
You have many options for templating like jade,ejs,hbs and so on.
If you use jade or any of them your html rendering code in express routes will get simplified.
without a templating engine
response.writeHead(200, {"Content-Type:": "application/json"});
var submittedPost = {};
submittedPost['message'] = 'Proof that Node and Mongo are working..';
response.write( "_wrapper('" );
response.write( JSON.stringify(submittedPost) );
response.write( "')");
response.end();
with a templating engine like jade (now pug)
var submittedPost = {};
submittedPost['message'] = 'Proof that Node and Mongo are working..';
response.json(submittedPost);
also with templating engines you can render templates with server side variables and you can access them inside your templates like
app.get('/mypage', function (req, res) {
res.render('mytemplate_page',{template_variable:some_variable});
});
and you can use template_variable inside the template for looping through or displaying.