Ajax fetching HTML not SQL results from node.js - node.js

I am trying to send my sql query results from node.js to my html. When I log it in the console it shows the correct data, but once I add it to the "res.send" in a stringified format and try to retrieve it with ajax in index.html the object I get doesn't have the data, just my entire HTML code.
I've tried changing my ajax to many different things I found online but nothing changes. I've tried changing POST to GET, changing the url (which just breaks it), only using success and not complete (which results in no object coming through).
node.js code excluding server code:
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=NAME-PC\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT * FROM Companies', (err, result) => {
console.log("Works");
if(err) { // SQL error, but connection OK.
console.log(" Error: "+ err);
JSON.stringify(err);
} else { // All good.
console.dir(result);
JSON.stringify(result);
app.get('/', function data(req, res, next) {
res.send(JSON.stringify(result))
})
};
});
});
sql.on('error', err => { // Connection bad.
console.log("Bad");
console.log(" Error: "+ err);
});
HTML Ajax code:
<script>
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: 'json',
url: '/',
contentType: "application/json; charset=utf-8",
complete: function(data) {
console.log(data);
},
success: function(data){
console.log(data);
}
});
</script>
The object I end up with has a responseText that has all of the HTML code. Any idea what I am doing wrong that the response isn't my data?

Related

Issue getting correct POST data to save to mongodb from axios even though the console.log shows valid data

I am having issues getting data to save to my mongoDB through a post. I am able to get it to show correctly in a console.log but i'm not getting the data to the DB successfully.
The axios code:
async created() {
axios
.get("https://api.coinmarketcap.com/v1/ticker/?limit=2000")
.then((res, err) => {
if (res.status === 200) {
this.$store.state.CMC = res.data[0].coins;
// console.log(this.$store.state.CMC);
// Send a POST request
axios({
method: "post",
url: "http://localhost:5000/data",
data: { coins: this.$store.state.CMC }
}).catch(err, function() {
console.log(err);
});
} else {
console.log("Error: " + err);
}
});
}
The express code for the POST:
app.post("/data", (req, res) => {
console.log(req.body);
var Coins = new coins(req.body);
Coins.save(req.body, function() {
console.log("data was saved");
});
});
Like i said, i can see the data being shown in the clog when i go to post it, it's just not saving correctly.

Simple Json Request never succeeds

I have a very simple Express server with a single route. I want to call this route with ajax from my html page and return json to the page.
The server side function gets called successfully but the failure method of the ajax method gets called the whole time. It never succeeds.
NodeJs
app.get('/test', function(req, res) {
console.log("TEST WAS CALLED");// This Logs to Console
res.json({ message: 'Hello World' });
});
Client Ajax
function FetchData(callbackfn) {
$.ajax({
type: "GET",
url: "http://localhost:3000/test",
async:false,
cache:false,
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
callbackfn("Error getting the data")
}
});
}
function Callback(data) {
alert(data);
}

Facebook photo uplaod is not working with electron + nodeJS

Application Stack : Facebook Photo Upload + Graph API v.2.8 + Electron + NodeJS + ReactJS
I am trying to implement Facebook photo sharing in my application. I got Facebook Login working manually due to some electron JS issues with reactJS.
All other Facebook endpoints are working like : /me/feed, /me/post etc
But /me/photos is not working as expected.
Its uploading an already hosted image on internet with http url but when i try to add local file into the request it didn't work.
I have used nodeJS Library => facebook-node-sdk but got no luck.
With facebook-node-sdk it updated user feed with messages and other requests but image upload didn't work. It gives me this error :
TypeError: self._form.on is not a function
And I figured out the issue here : Node Facebook Issue
I used this code with facebook-node-sdk :
FB.setAccessToken(ACCESS_TOKEN);
domtoimage.toBlob(node, { height: node.scrollHeight }).then(function (imageData) {
FB.api('me/photos', 'post', {
access_token: ACCESS_TOKEN,
url: 'https://www.facebook.com/images/fb_icon_325x325.png', // This one works fine
// This one below shows error : 'TypeError: self._form.on is not a function'
url: fs.createReadStream(`${SHARE_IMAGE_PATH}shareFile.png`),
// I tried also with Blob Object as :
url: imageData,
caption: 'Share',
debug: 'all'
}, function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log('Post Id: ' + res.post_id);
});
}).catch(function (error) {
console.error('oops, something went wrong!', error);
});
Then I tried with https nodejs request like below :
domtoimage.toPng(node, { height: node.scrollHeight }).then(function (imageData) {
let photoBuffer = new Buffer(imageData.replace(/^data:image\/\w+;base64,/, ''), 'base64');
shareImagePathExists().then(exists => exists ? exists : createShareImagePath()).then(() => {
log.info('Saving Screenshot to ' + SHARE_IMAGE_PATH);
fs.writeFile(`${SHARE_IMAGE_PATH}shareFile.png`, photoBuffer);
}).then(() => {
let formData = {
access_token: accessToken,
url: 'https://www.facebook.com/images/fb_icon_325x325.png', // This one works fine
// This one below returns 'requires upload file error'
url: fs.createReadStream(`${SHARE_IMAGE_PATH}shareFile.png`),
caption: 'Share',
debug: 'all'
};
console.log(formData);
let postData = querystring.stringify(formData);
let post = {
host: 'graph.facebook.com',
path: '/me/photos',
method: 'POST',
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
'Accept': 'application/json'
}
};
let req = https.request(post, function (response) {
let result = '';
response.on('data', function (data) {
result = result + data;
});
response.on('end', function () {
if (response && response.statusMessage === 'OK') {
dispatch(facebookActivityShareComplete());
dialog.showMessageBox({
title: 'Share Success',
message: 'Activity Shared to Facebook.',
buttons: []
});
console.log('Response Success: ', response);
}
});
response.on('error', function (err) {
console.log('REQUEST ERROR: ' + err.message);
});
console.log('Response recieved: ', response);
});
dispatch(facebookActivitySharing());
req.write(postData);
req.end();
});
}).catch(function (error) {
console.error('oops, something went wrong!', error);
});
Above Code returns requires upload file error each time. I am using facebook graph API v2.8 I tried many solution like using request npm package for nodeJS but nothing seems to be working with uploading image from local file path or base64Data or Blob Object.
Any kind of assistance will be appreciated.
Thanks!
For Error :
Uncaught TypeError: self._form.on is not a function request.js:1134.
It looks like Electron Browser don't support the .on('error') call for request node package. And we can't use node-facebook-sdk here as it uses request at the back to send data requests. So, I tried some other packages and got it working with needle here. Then I did some more research to do a multipart/form request to upload image to facebook. And end up doing it like :
domtoimage.toBlob(node, { height: node.scrollHeight }).then(function (imageData) {
let form = new FormData();
form.append('filename', 'source');
form.append('file', imageData);
form.append('caption', CAPTION);
let request = new XMLHttpRequest();
request.open('POST', 'https://graph.facebook.com/me/photos?access_token=' + ACCESS_TOKEN);
request.send(form);
request.onload = () => {
if (request.status !== 200) {
console.log('Response : ', request.responseText);
}
};
}).catch(function (error) {
log.error('oops, something went wrong!', error);
});
And It worked fine.

SailsJS - Nodejs Https-Request. Can't set headers after they are sent

I'm new to Sails.js and I was trying to make a filter to authorize using a Bearer token which come from a higher server, a gatekeeper which is responsable to do the OAuth2 authentication from GitHub API. The services streams works well. I'm already aware of Passport.js but I'm trying to implement this on my own. I came with a policy which looks like:
module.exports = function (req, res, next) {
var httpsExec = require('https');
if (req.headers.authorization) {
var parts = req.headers.authorization.split(' ');
if (parts.length == 2) {
var tokenType = parts[0]
, credentials = parts[1];
if (/^Bearer$/i.test(tokenType) || /^bearer$/i.test(tokenType)) {
httpsExec.request({
host: 'api.github.com',
post: 443,
path: '/user',
method: 'GET',
headers: {'Authorization': 'token ' + credentials, 'User-Agent': 'curly'}
}, function (response) {
var responseData = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
responseData += chunk;
});
response.once('error', function (err) {
next(err);
});
response.on('end', function () {
try {
req.options.user = JSON.parse(responseData);
next();
} catch (e) {
res.send(401, {error: e});
}
});
}).end();
} else {
console.err("The token is not a Bearer");
res.send(401)
}
}
} else {
res.send(401, {error: "Full authentication is necessary to access this resource"})
}
};
The policy is called once I hit the controller route but it throws a _http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
And the process is terminate.
The problem I think is the next() and the returns I tried everywhere I think, to put the next() call, but still gives me this error, if I remove then I lock the request on the policy.
EDIT
I did a simple sample of policy where I just set some property on req.options.values and happened the same problem, so maybe could be an issue with req.options.requestData = JSON.parse(responseData); ? How else could I set a property to send to controller ?
response.once('error', function (err) {
next(err);
});
response.on('end', function () {
try {
req.options.user = JSON.parse(responseData);
next();
} catch (e) {
res.send(401, {error: e});
}
});
both are getting executed.to check console.log("something") in error to see if there is error.
This happens when you're trying to modify the request and response together or modify one of them twice.
In your code, I think the callback is being called twice and you are also modifying the response at the same time. Check the lines where you're calling callback "next()". You'll find your issue.

How To Make an Ajax Request inside a Azure Mobile Services api

I want to make a jquery ajax post inside my azure mobile services api get method. that is, something like I have below. That is, I want the GET method to return data that returns something from ithe result of my ajax POST.
It's not obvious how I would do that.
exports.get = function(request, response) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function(x) { return MYLIST },
dataType: dataType
});
response.send(statusCodes.OK, { message : 'Hello World!' });
};
UPDATE:
Per Carlos Post : http://blogs.msdn.com/b/carlosfigueira/archive/2013/12/12/expanded-login-scopes-in-azure-mobile-services.aspx I now understand that the exports.get code should be in the API section of the azure mobile service. When I put that code into that section I get an Internal Error, 500 in my failure event of the jquery call. my alert does show I successfully logged into google.
var client = new WindowsAzure.MobileServiceClient('https://svcc.azure-mobile.net/', val);
$(document).ready(function () {
$("#submit1").click(function () {
client.login("google").done(function (results) {
alert("You are now logged in as google: " + results.userId);
$.ajax({
url: "http://xxxxx.azure-mobile.net/api/test1",
success: function (data, textStatus) {
debugger;
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
}, function (err) {
alert("Error: " + err);
});
});
You should use some node.js module which allows you to make HTTP requests. The simplest one is the 'request' module, which you can require on a server script and use it to make requests. For example, this code should do what you want:
exports.get = function(request, response) {
var req = require('request');
req({
url: url,
method: 'POST',
body: JSON.stringify({ theBody: [ 'hello', 'world' ]}),
headers: { "Content-Type": "application/json" }
}, function(err, result) {
response.send(statusCodes.OK, result);
}
}

Resources