How to make ajax get/post request in express server? - javascript

Below is my express server. I am trying to make a get request in ajax, but it turned out failed even though I required jquery at the beginning. It said $ is not defined Other than using jquery ajax, what else can I use to make an API call form RESTful API url?
var express = require('express');
var requestHandler = require('./requestHandler');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname, '../client')));
app.get('/homepage', requestHandler.getData);
var port = process.env.PORT || 3000;
app.listen(port);
console.log("Server running at: http://localhost:" + port);
// request handler file:
var express = require('express');
var url = "http://jsonplaceholder.typicode.com/";
module.exports.getData = function (req, res){
$.ajax({
method: 'GET',
url: url+'posts',
success: function(data) {
console.log(data);
res.send(data);
}
});
}
module.exports.getComments = function(userId){
$.ajax({
method: 'GET',
url: url+'/comments',
success: function(data) {
console.log(data);
}
});
}

HTTP GET Request in Node.js Express
var http = require('http');
var options = {
host: 'www.google.com',
path: '/index.html'
};
var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
// ...and/or process the entire body here.
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});

You need to understand things like:
expressjs is serverside code so it can't use jquery ajax like that.
jQuery.ajax() can only be used at view when you load your page in the browser.
You need to use some view engines like jade to create templates and use routers to push the view in the browser. When you have your view in the browser then you can make a reference to the script file which can contain your ajax code to let you have posts and comments.
More information.

Try something like this:
function() {
// Simple POST request example (passing data) :
$http.post("/createProject/"+ id +"", {
projectTitle: pTitle,
userID : id
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$scope.getProjects();
console.log("project created");
console.log("this is the response data " + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
Also please note. you will call this from an external JavaScript file. One the express server you will only have "routes" and from external javascript files you can perform HTTP calls on those routes.

Update
#Someone, the express framework is very popular to setup a web server in Node. You can use different render engines to render the view and pass information to the user. This is a very simple example from the Express website listening to two urls (/posts and /comments).
var express = require('express');
var app = express();
app.get('/posts', function (req, res) {
res.send('Render posts!');
});
app.get('/comments', function (req, res) {
res.send('Render comments');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Related

How to save data from JSON to a variable in NodeJS

I'm new in Node.js, I have a problem.
I would like to save data from JSON object which I have downloaded from github API.
var http = require("http");
var express = require('express');
var app = express();
var github = require('octonode');
var client = github.client();
app.set('port', process.env.PORT || 8000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
app.get('/getUsers', function (req, response) {
response.writeHead(200, {'Content-Type': 'text/json'});
var result;
client.get('/users/angular/repos', {}, function (err, status, body, headers) {
result = response.write(JSON.stringify(body));
console.log(result); //JSON object
return result;
});
console.log(result); //undefined
});
How can I save an data from object to single variable?
(I want to then transform it to an Array and take some useful data).
You will not get result outside of the asynchronous call as it is not yet defined. To get this value either call a method inside the callback of query or use async module and pass it.
app.get('/getUsers', function (req, response) {
response.writeHead(200, {'Content-Type': 'text/json'});
var result;
client.get('/users/angular/repos', {}, function (err, status, body, headers) {
result = response.write(JSON.stringify(body));
console.log(result); //JSON object
doSomeOperationOnResult(result)
});
});
function doSomeOperationOnResult(result){
//Your operating code
}

How to connect my website to my node app?

So I am trying to send test data to my node app using ajax. I'm not sure what I'm doing wrong to post the information. I have added this to my script to my html:
index.html
<script type="text/javascript">
jQuery(function() {
console.log('hello');
var $ = jQuery;
$(window).ready(function() {
console.log('hello');
$.ajax({
dataType: 'jsonp',
xhrFields: {
withCredentials: true,
},
url: 'http://localhost:3000',
data: '{"data": "TEST"}',
type: 'POST',
success: function () {
console.log('Success: ');
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
},
});
});
});
</script>
I am trying to receive this information from my node app but I'm not sure how to.
server.js
var express = require('express')
, cors = require('cors')
, app = express()
, http = require('http');
app.use(cors());
var server = http.createServer(app, function(req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log(body);
res(body);
});
}).listen(3000, function(){
console.log('CORS-enabled web server listening on port 80');
});
However, I keep getting this error on website's console:
'GET http://localhost:3000/?callback=jQuery214011563337640836835_1442781076103&{%22data%22:%20%22TEST%22}&_=1442781076104 n.ajaxTransport.a.send # jquery.js:8698n.extend.ajax # jquery.js:8166(anonymous function) # final.html:534n.Callbacks.j # jquery.js:3099n.Callbacks.k.fireWith # jquery.js:3211n.extend.ready # jquery.js:3417I # jquery.js:3433
final.html:550 Error: undefined'
If this is successful I am trying to create a form that posts the input to my node app that can process it with stripe.
I recommend following the Express JS Getting Started guide found here: http://expressjs.com/starter/installing.html. Specifically, look at the sections on Express generator and Basic routing.
In your code, you are requiring the Express module, but not actually using it, and this module is the most robust way to handle posts in node.js.
If you still want to use the http module for handling post requests, check this out: Node.js server that accepts POST requests. It also has more information on using Express JS

How to post data from my html page to a listener?

I'm currently designing a UI for an Automated Parking System. I currently need to test if my page sends out data from a form by sending it to a listener. I currently have this code but I'm not sure why it isn't working. Any help would be greatly appreciated.
This is my code that sends the data to a local listener.
<script>
var INPARK = {cardID: $("#ticket_num").val(), lift: 1, floor: 1};
$.ajax({
type:"POST",
url: '192.168.150.148:5007',
contentType:"application/json",
data: JSON.stringify(INPARK)
});
</script>
This is the listener code.
var HOST = '192.168.150.148'; // This should be your IP of 192.168.150.XXX
var PORT = 5007;
var http = require('http');
http.createServer(function (req, res) {
// Only listen for POST requests
if (req.method === 'POST') {
var buffer = '';
req.on('data', function (chunk) {
buffer += chunk;
});
req.on('end', function () {
var path = req.url.substring(0, req.url.indexOf('/', 1)).toUpperCase();
var json;
try {
json = JSON.parse(buffer);
} catch (err) {
//
}
if (path === '/INPARK') {
// Handle INPARK request
console.log(json);
res.write('inpark results');
} else if (path === '/OUTPARK') {
// Handle OUTPARK request
console.log(json);
res.write('outpark results');
} else {
// Do nothing - Bad request
res.write('BAD REQUEST');
}
// Close the connection
res.end();
});
}
}).listen(PORT, HOST, function () {
console.log('Listening at %s:%s', HOST, PORT);
});
Your ajax request is most likely going from port 80 or 443 to 5007, which is a cross domain request, hence it will fail,
If you want to resolve this issue, read up on CORS:
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing,
and JSONP:
https://en.wikipedia.org/wiki/JSONP

node.js / jQuery cross domain: ERR_CONNECTION_REFUSED

I'm new to Node.js.
I'm creating a simple node/express application that serves a single web page containing one button that when clicked makes a jQuery ajax request to an Express route.
The route callback makes an http.get request to openexchangerates.org for some json data containing foreign exchange rates. The JSON is then output to the Developer Tools console window.
The application works on the first button click, but on any subsequent clicks the console window displays:
GET http://127.0.0.1:3000/getFx net::ERR_CONNECTION_REFUSED
A screen grab of the Developer Tools console window shows the result of the first click, and then the second click when the connection is refused.
The error detail is as follows:
GET http://127.0.0.1:3000/getFx net::ERR_CONNECTION_REFUSED jquery-2.1.3.min.js:4
n.ajaxTransport.k.cors.a.crossDomain.send jquery-2.1.3.min.js:4
n.extend.ajax (index):18
(anonymous function) jquery-2.1.3.min.js:3
n.event.dispatch jquery-2.1.3.min.js:3
n.event.add.r.handle
My simple Node/Express application is as follows:
var express = require('express');
var app = express();
var http = require("http");
var data = "";
var json;
console.log( "__dirname", __dirname );
app.use( express.static( __dirname + '/') );
var options = {
host:"openexchangerates.org",
path:"/api/latest.json?app_id=<get free ID from openexchangerates.org>"
};
app.get("/", function( req, res ) {
res.sendFile('index.html', { root: __dirname });
})
app.get("/getfx", function(req, res) {
console.log("Route: getFx");
getFx(res);
})
function getFx(res) {
console.log("http getFx");
http.get(options, function (response) {
response.on("data", function (chunk) {
//console.log("data:\n"+chunk);
data += chunk;
});
response.on("end", function () {
json = JSON.parse(data);
console.log("http response end:");
res.end( data );
});
response.on("error", function (e) {
console.log("error:\n" + e.message);
});
})
}
app.listen(3000);
My html index page is:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Get FX</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
console.log( "document ready");
$("#btnFx").click(function() {
console.log('clicked', this );
$.ajax({
url : "http://127.0.0.1:3000/getFx",
dataType : "json",
success : function(json) {
console.log("json returned:\n", json);
}
});
} );
})
</script>
</head>
<body>
<button id="btnFx" style="width:200px">Get foreign exchange rates</button>
</body>
For openexchangerates.org to serve the data, a free app id is required. Anyone able to help resolve this may have to go through their very short sign up:
That link is here:
https://openexchangerates.org/signup/free
However it's possible that my mistake is glowingly obvious to those with better Node/Express/jQuery knowledge.
Many thanks in advance
The way you defined your data and json vars is causing subsequent requests to fail. Since you defined them up front, all requests will re-use them, meaning by the time you JSON.parse data for the second request, data will contain two valid json strings, thus making one invalid json string. To fix this, define data and json farther down in the callback.
var express = require('express');
var app = express();
var http = require("http");
//var data = "";
//var json;
console.log( "__dirname", __dirname );
app.use( express.static( __dirname + '/') );
var options = {
host:"openexchangerates.org",
path:"/api/latest.json?app_id=<get free ID from openexchangerates.org>"
};
app.get("/", function( req, res ) {
res.sendFile('index.html', { root: __dirname });
})
app.get("/getfx", function(req, res) {
console.log("Route: getFx");
getFx(res);
})
function getFx(res) {
console.log("http getFx");
http.get(options, function (response) {
var data = "";
var json;
response.on("data", function (chunk) {
//console.log("data:\n"+chunk);
data += chunk;
});
response.on("end", function () {
console.log("http response end:");
json = JSON.parse(data);
res.json(json);
});
response.on("error", function (e) {
console.log("error:\n" + e.message);
});
})
}
app.listen(3000);
Issue comes from Cross origin requests protection which happens on localhost with chrome. Try to use other browser or just Allow origin to all hosts (*) or your host (http://localhost:3000):
app.use( express.static( __dirname + '/') );
app.use(function(req,res,next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});

Problems using Parse.Cloud.httpRequest with Express, says no such method for success:

I'm hitting a facebook graph search URL, in Parse Express. The call is made with a Parse.Cloud.httpRequest.
I get a 500 Internal Server Error response, and when I look in the logs I see:
an error saying that the httpRequest has no method named success: (even though the code i'm using is based right off examples on Parse.com).
The basic JSON data is there successfully retrieved but the error has prevented the function completing.
Here's the code, all tips appreciated:
// These two lines are required to initialize Express in Cloud Code.
var module = require('cloud/jsonml.js');
var Buffer = require('buffer').Buffer;
var express = require('express');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views'); // Specify the folder to find templates
app.set('view engine', 'ejs'); // Set the template engine
app.use(express.bodyParser()); // Middleware for reading request body
app.get('/hello', function(request, response) {
Parse.Cloud.httpRequest({
url: 'a-facebook-graph-url',
success: function(httpResponse) {
console.log(httpResponse.data);
response.success(httpResponse.data);
var xml = module.stringify(httpResponse.data);
var base64xml = xml.data.base64;
console.log(base64xml);
res.render('hello.ejs',{ message: base64xml });
},
error:function(httpResponse){
console.error('Error:' + httpResponse.message);
response.error("Failed to parse feed");
res.render('hello.ejs',{ message: httpResponse.message });
}
});
});
app.listen();
I just use promises. This seems to work for me:
Parse.Cloud.httpRequest({
url: 'a-facebook-graph-url'
}).then(function(httpResponse) {
console.log(httpResponse.text);
var xml = module.stringify(httpResponse.data);
var base64xml = xml.data.base64;
res.render('hello',
{
message: base64xml
});
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
});
More info from parse website here

Categories