GET request, with data - javascript

What is the equivalent of the following browser-side GET request in Node?
jQuery.ajax({
url: 'http://test.com',
type: 'GET',
data: myData,
success: function(data) {
console.log(data);
}
});
My best attempt is
http.get('http://test.com', function(response) {
response.on('data', function (chunk) {
console.log(chunk);
});
});
The problem is I don't know how to pass data: myData in the Node version. How can I pass data to http.get requests?

You have to pass it the full URL. you can create the URL by adding the query parameters yourself. There is a helper for making your own Query Strings. So it would be something like:
url = "http://test.com/?" + querystring.stringify(myData);
http.get(url, ...);

Remember that the get method is by url, so you can add it to the url if you want
http.get('http://test.com?GetVariable='+myVal, function(response) {
response.on('data', function (chunk) {
console.log(chunk);
});
});

Related

How to return database data in HTTP get method

In server side,I fetch data from database
var sql = require('mssql');
app.get('/api/comments', function(request, response) {
var sqlConfig = {
// Connection string parameters.
}
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = 'select TOP 10 * from comment';
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
sql.close();
response.json(recordset);
});
});
});
Then,I fetch the data from server side by AJAX (get method)
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
success: (comments) => {
this.setState({ comments })
}
});
I get an error when I get the data by Ajax.
(Uncaught TypeError: this.state.comments.map is not a function)
It seems that the data return is undefined.Instead of fetching database,the code is work if I use static data(hard code) in server side.
I think the problem is the callback function in sql.connect() but I have no idea how to solve it.Does anyone can help?
Error:
The solution is adding dataType: 'json' to the ajax
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
dataType: 'json',
success: (comments) => {
this.setState({ comments })
}
});
}

How to render a page from an AJAX POST request?

I make a POST AJAX request:
firebaseAUTH.currentUser.getToken(true).then(function(idToken) {
$.ajax({
// Send token to your backend via HTTPS (JWT)
url: '/auth',
type: 'POST',
data: {token: idToken},
success: function (response) {
var userID = response.userID
firebaseDB.ref('/users/' + userID)
.once('value')
.then(function(snapshot) {
$.post('/members-area/' + userID, snapshot.val(), function(data, status) {
});
});
}
});
});
My handler:
app.use('/members-area/', function(req,res,next) {
console.log(req.body) //works well and gives object
res.render('members-area', { Snapshot: req.body})
})
However, it does not render the page. Why is that and how can I achieve that?
I can't move that function call outside of the success attribute of the AJAX call, as then the decoded userID variable would not be available.

res.send not working properly

I am working with a simple CRUD app with jquery ajax and node.js, just to improve my skills with node and ajax. The thing is that I am doing a post request that is handled with my post router in the node server, and everything is working fine. It adds 1 more product to my products.json file, but in the end it doesn't send the response back to the client, the final res.send("done") doesn't work and I don't know why..
here is the code:
ajax
$("#create-form").on('submit',function(){
event.preventDefault();
var createIn = $("#create-input").val();
$.ajax({
url: '/products',
method:'POST',
data:JSON.stringify({name:createIn}),
contentType: "application/json",
dataType: "json",
success: function(data){
console.log(data);
$("create-input").val("");
$("get-button").click();
}
});
})
node
app.post('/products',function(req,res){
fs.readFile('products.json','utf8',function(err,data){
var result = JSON.parse(data);
var productName = req.body.name;
console.log(req.body.name);
currentId++;
var productId = currentId;
var product = {
name: productName,
id: productId
}
result.products.push(product);
fs.writeFile(__dirname + "/products.json",JSON.stringify(result),'utf8');
});
res.send("post done");
});
This is just the important part of the code, it works and just fails at the end in the res.send.
Your client code is looking for a json response, but you are returning a string.
$("#create-form").on('submit',function(){
event.preventDefault();
var createIn = $("#create-input").val();
$.ajax({
url: '/products',
method:'POST',
data:JSON.stringify({name:createIn}),
contentType: "application/json",
dataType: "json", <--------------
success: function(data){
console.log(data);
$("create-input").val("");
$("get-button").click();
}
});
})
Either delete this line or add on the server side
res.send({"message":"post done"});
This does not answer your question directly but you should ideally not send back the response until you know the work has been done, and you should handle errors. In other words you should use the callbacks. (Too many callbacks can be problematic and you should investigate other patterns - eg promises - bit no need here)
app.post('/products',function(req,res){
fs.readFile('products.json','utf8',function(err,data){
if (err) return res.send("error");
var result = JSON.parse(data);
var productName = req.body.name;
console.log(req.body.name);
currentId++;
var productId = currentId;
var product = {
name: productName,
id: productId
}
result.products.push(product);
fs.writeFile(__dirname + "/products.json",JSON.stringify(result),'utf8', function(err, res) {
if (err) return res.send("error");
res.send("post done");
});
});
});

Method being called before Promise is complete

I am attemting to add an item to a sharepoint list from an Apache Cordova application. It first prompts the user to login then it will make a HTTP Post to so the data entry.
I have the following code:
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(FormatAndUpload(authResult, data), errorCallback);
}
function FormatAndUpload(authResponse, data) {
var token = authResponse.accessToken;
var expiry = authResponse.expiresOn;
console.log("Token acquired: " + authResponse.accessToken);
console.log("Token will expire on: " + authResponse.expiresOn);
$.ajax({
url: "https://my.sharepoint.com/_api/web/lists/getbytitle('" + Test + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"Authoriztion":"Bearer " + token
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
The problem I am having is that the FormatAndUpload method is being called before acquireTokenAsync has completed, so the authResponse variable passed into the FormatAndUpload method is null.
I'm not too familiar with the promise framework in Javascript/JQuery but I was under the impression that the event should only fire on completion of the previous method.
Does anyone have any pointers in how I can correctly wait for the login to complete before attempting the POST?
what you did FormatAndUpload(authResult, data); is wrong the correct way to pass a callback is
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
so your saveToSharepoint will be like this
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
}
Thanks for the answer Newbee Dev, you were correct in that I didn't formulate the then method correctly.
For any others who see this regarding SharePoint, I actually reformatted the code for it to work as expected, so the saveToSharepoint method looks like so:
function saveToSharepoint(data) {
var AuthenticationContext = Microsoft.ADAL.AuthenticationContext;
AuthenticationContext.createAsync("https://login.microsoftonline.com/common/")
.then(function (authContext) {
authContext.acquireTokenAsync(
"https://my.sharepoint.com", // Resource URI
"4be098f8-2184-4831-9ef7-3d17dbbef6a0", // Client ID
"http://localhost:4400/services/office365/redirectTarget.html" // Redirect URI
).then(function (authResult) {
FormatAndUpload(authResult, data);
}, function (err) {
console.log(err);
});
}, function (err) {
console.log(err);
});
}
The main thing to note is creating the AuthenticationContext asynchronously and this way, the FormatAndUpload calls after the whole login process is complete. Just thought I would post this for other people who see this regarding Sharepoint and are stuck.

jQuery ajax calls with nodeJS

These are my code blocks.
API Endpoint
app.get('/clients/zvb/:id', function(req, res) {
console.log('ZVB Query loaded as var = file;')
var path = './public/queries/zvb.sql'
var zvb = fs.readFileSync(path, "utf8")
zvb = zvb.splice(25, 0, req.params.id)
request.query(zvb, function(err, recordset) {
console.log(recordset);
res.end(JSON.stringify(recordset));
});
})
Then my index.html where I try and GET the data from the endpoint.
$.ajax({
type: 'GET',
url: 'http://localhost:8081/clients/zvb/16601',
dataType: 'jsonp',
success: function(data) {
console.log(data);
console.log('we got to here..')
}
});
Not much is happening at the moment. When I try and manually run the ajax call in the terminal I get;
Object {readyState: 1}
The endpoint is working, if I view it I can see the JSON i'm after.
Tom
If you are using jquery 1.5+ these shorthand methods are very easy to use.
(I can't comment or would have asked). Doc is here http://api.jquery.com/category/ajax/shorthand-methods/
$.get( "http://localhost:8081/clients/zvb/16601", function(data) {
var data = JSON.parse(data);
})
.done(function() {
})
.fail(function() {
})
.always(function() {
});

Categories