ajax post with jquery to mongodb - javascript

I want to make a Post request using jQuery to mongodb.
running on app localhost:3000.
Using mongoose I can get to display movies using:
router.get('/', function(req, res, next) {
mongoose.model('Movie').find(function(err, titles){
res.render('testdb', { title: 'MYMusic',
className: 'index',
names: titles
});
console.log('names: ', titles);
});
});
But when I want to dynamically post to my database using jQuery using:
$('.save-video-button').on('click', function(event) {
var obj = {
title: 'some title'
};
var URL = 'mongodb://localhost/mydatabase';
$.ajax({
url: URL,
type: "POST",
data: JSON.stringify(obj),
contentType: "application/json",
success: function(data) {
console.log('success --> data :', data);
},
error: function(xhr, text, err) {
console.log('error: ',err);
console.log('text: ', text);
console.log('xhr: ',xhr);
console.log("there is a problem whit your request, please check ajax request");
}
});
});
when I run this ajax request it get an error shown in google chrome dev tools console:
XMLHttpRequest cannot load mongodb://localhost/mydatabase. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
How can I avoid this cross origin request?
Thank you!

ok I got it! for anyone with the same question DO NOT forget to have a router.post in you server side:
router.post('/', function(req, res){
var newmovie = res.body;
console.log(newmovie);
});
so when you make the call you can actually pass the data = res.

Related

transform $.get to node.js request

i'm using geolocation, i was handling everything on client side, now I wat to handle this from
Currently using it as;
var url = "youtube.com",
options = {
key: API_KEY,
video: "vid_id"
};
$.get(url, options, function(data) {
console.log(data)
})
I want to use it with nodeJS HTTPS, so i tried;
var https = require("https"),
url = "youtube.com",
options = {
key: API_KEY,
video: "vid_id"
};
https.get(url, options, function(data) {
console.log(data)
})
but i cant get it work I hope someone can convert this.
Try using the request module for node.js. Install it by running:
npm install request.
var request = require('request');
request(`youtube.com/?key=${key}&video=${video_id}`, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('body:', body); // Print body of the response.
});

Alternative way of sending array to NodeJS using AJAX

So I've had a lot of problems with sending arrays to NodeJS using AJAX, when sending it with JSON, the error function always gets called (asking why that is has given me no answer that I could use).
So I was wondering if anyone knows a different approach to this, the one that I have right now is:
$.ajax({
type: 'POST',
url: 'http://localhost:1337/deposit?steamid=' + steamid,
contentType: "application/json; charset=UTF-8",
dataType: 'json',
data: JSON.stringify({arr:items}),
success: function(data) {
console.log("Tradeoffer has been sent");
},
error: function(data) {
alert("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
console.log("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
}
});
And on the server side:
app.post('/deposit', function(req, res) {
console.log('Deposit request recieved, info:');
console.log('STEAM ID: ' + req.query.steamid);
console.log('ITEMS: ' + req.body.arr);
});
So I was wondering if someone could tell me another way of sending an array.
If you can tell me what's wrong with this code, that would be awesome to of course.
app.js
//nodejs v4.2.6
var express = require('express');
var app = express();
var fs = require('fs');
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.get('/test', function(req, res) {
fs.readFile('test.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.post('/deposit', function(req, res) {
console.log('Deposit request recieved, info:');
console.log('STEAM ID: ' + req.query.steamid);
//console.log('ITEMS: ' + req.body.arr);
res.send({'finish':'finish'});
});
app.listen(3000, function(){
console.log('http Express server(worker) listening on port 3000');
});
test.html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
</head>
<body>
<script>
var steamid = 1;
$.ajax({
type: 'POST',
url: 'http://localhost:3000/deposit?steamid=' + steamid,
contentType: "application/json; charset=UTF-8",
dataType: 'json',
data: JSON.stringify({arr:[1,2,3,4]}),
success: function(data) {
console.log("Tradeoffer has been sent");
},
error: function(data) {
alert("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
console.log("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
}
});
</script>
</body>
</html>
I think that you listen to the wrong URL in Node. From AJAX you call url: http://localhost:1337/deposit?steamid=' + steamid,, but you listen to '/deposit' in Node.
You could try using RegExp:
app.post(new RegExp('/deposit?steamid=[a-zA-Z0-9]')
(assuming that `steamid only contains alphanumerical characters).
Since you're not sending a GET request you might as well get rid of the steamid parameter in the URL and call http://localhost:1337/deposit/' + steamid,; you should then listen to app.post(new RegExp('/deposit?steamid=[a-zA-Z0-9]') in Node.
Hope this helps!

Update content of page from a POST request in Express

I had a problem where I tried to update the contents of the web page through a POST request that was done through a form but the problem is that the variables were set to the global scope and every time that I refreshed the page the content was still there. Somebody explained what was the issue and told me that I could "...make the post return a JSON object with the data instead of doing a redirect. Then do the POST async from the client and display the data." Here is the code that I'm using on:
Express:
var data;
var url;
/* GET home page. */
router.get('/', (req, res, next) => {
res.render('index', { 'data': data});
});
/* POST HANDLER */
router.post('/link', function(req, res, next) {
var pattern = /^((http|https|):\/\/)/;
url = req.body.link;
if (!pattern.test(url))
{
url = "http://" + url;
bitly.shorten(url)
.then(response => {
data = response.data.url;
res.redirect("/");
});
}
});
And I'm using jQuery for the POST request:
$('#shortLink').on('click', () => {
$.ajax({
type: 'POST',
url: '/link',
data: {link: $('#linkInput').val()},
success: data => {
console.log(data);
}
});
});
What I want to do is get the value of an input, send it to the POST handler on Express and then pass that information back to the home page without having to get out of the page; like a common Ajax request. Can somebody elaborate on what I was suggested to do, above? Or give me another solution.
There's no rule that says you have to redirect after handling a post request. Just send the data back via res.json({'url': response.data.url}), and then in your $.ajax success handler it will be available via data.url.

MYSQL + Node.JS Post Request Confusion

I am very new to networking and I have this code which, when I use a REST API like Postman, does exactly what I want it to do:
router.post('/', function(req,res,next){
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function(err, conn){
if(err)
{
console.error('SQL Connection error: ', err);
return next(err);
}
else
{
var query = conn.query("INSERT INTO coordinates (id,lat,lon) VALUES(3,2,1);");
if(err)
{
console.error('SQL error: ', err);
return next(err);
}
res.json("Coordinates sent.");
}
})
} );
That is, it sends the query request to the MYSQL database. My question is, how do I do this without using Postman to send the POST request?
Thank you.
You can't unless you make a post request from within your application or something. If you don't intend on sending data, you can just make it a GET request by changing
router.post('/', function(req,res,next){
to
router.get('/', function(req,res,next){
Then you can just go to the relevant URL from your browser. If you're using chrome and you just wanna see the JSON data, I'd also recommend installing the JSONView chrome extension.
EDIT
Here's the example request using request-promise
var request = require('request-promise');
var objectData = {
name: 'Bruce',
alias: 'Batman'
};
var options = {
method: 'POST',
uri: 'http://your.api/endpoint/',
body: objectData,
json: true // Automatically stringifies the body to JSON
};
request(options).then(function(response){
// handle success response
}, function(error){
// handle error response
})

Send multiple variables to Node.js server with JQuery AJAX

When I try to log the data that was received by the server it is displayed as one long string. Instead I would like the received data to be seperable as different variables.
Client code
function sendData() {
var datas = { testdata: "TEST", testdata2: "TEST2" };
$.ajax({
url: 'server',
data: JSON.stringify(datas),
type: 'POST',
success: function (data) {
$('#lblResponse').html(data);
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
}
});
}
Server code
var http = require('http');
http.createServer(function (req, res) {
console.log('Request received');
res.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
req.on('data', function (chunk) {
console.log('GOT DATA!');
var receivedData = JSON.parse(chunk);
console.log(receivedData);
});
res.end("hello");
}).listen(1337);
I would like to be able to call for a single variable to get the value from it in the server. For example console.log(testdata); should display the value "TEST".
By stringifying your data object, you're sending a string to the server as the request body, and it's probably encoded using the "application/x-www-form-urlencoded" encoding.
You probably shouldn't JSON.stringify(datas), just use datas.
You need to parse the request body on the server. For that you could use a module like body

Categories