MYSQL + Node.JS Post Request Confusion - javascript

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
})

Related

nodeJs basic authentication issue

I'm getting no proper response while make an API request to external API using basic authentication (username and password) in nodejs (javascript)
I used the below code and the response is "undefined", not sure what is missing here.
But I was able to make a request using postman tool without any issues.
const request = require('request')
const user = '*****';
const pass = '*****!';
const url = 'https://servicenow.com/api/table'
var options = {
url: url,
auth: {
username: user,
password: pass
}
};
request.get(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(body.url);
console.log(body.explanation);
});
Response:
undefined
undefined
if your api right with postman you can do like this based on photo
send a request
click on code
select nodejs- Request
copy

How to consume a REST api that needs username/password authentication in node.js

I want to consume a REST api that needs a username/password authentication in node.js. The code that consumes the api is as follows:
var request = require('request');
var url = 'http://localhost:3000/api/v1/login/'
request.get(url,{'auth': {'user': 'test35','pass': 'mypassword','sendImmediately': false}},function(err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
}
console.log('Post successful! Server responded with:', body);
});
With the above code, the error I get is:
{
"status": "error",
"message": "API endpoint does not exist"
}
The api is written in meteor restivus and you can see it in the following question's answer here
In the API, when I remove the api's authRequired: true, i.e, remove
{
routeOptions: {
authRequired: true
}
}
and in the code that consumes the API above, change url from
'http://localhost:3000/api/v1/login/
to:
http://localhost:3000/api/v1/articles/
and run "node accessRESTapi.js", I am able to consume the REST api! What I am not able to do correctly is the authentication when "authRequired: true" is set as per above! Please help
EDIT: Updated based on info from comments
The style of request is quite different between logging in to get a token and the subsequent requests:
For login
The docs specify that login actions must be done with a POST request to /api/login/ with a body that contains username or email and password as url-encoded params
var request = require('request');
var url = 'http://localhost:3000/api/v1/login/'
var user = 'test35';
var pass = 'mypassword';
// Save these for future requests
var userId;
var authToken;
// Use POST instead of GET
request.post(
{
uri: url,
// I'm using form because it matches the urlEncoding behaviour expected by `restivus`
form: { username: user, password: pass }
},
function(err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
}
var json = JSON.parse(body);
authToken = json.data.authToken;
userId = json.data.userId;
console.log('Post successful! Server responded with:', body);
}
);
For future requests
Now you need to set the correct headers with the previously saved userId and authToken
According to the docs, that means X-User-Id and X-Auth-Token headers on all subsequent requests
var request = require('request');
var url = 'http://localhost:3000/api/v1/articles/'
request.get({
uri: url,
headers: {
'X-User-Id': userId,
'X-Auth-Token': authToken
}
}, function(err, httpResponse, body) {
if (err) {
return console.error('get failed:', err);
}
console.log('Get successful! Server responded with:', body);
});
Putting it together:
We want to make sure we get the authToken before making any further requests.
This means making the second request in the callback of the first function like so:
var request = require('request');
var url = 'http://localhost:3000/api/v1/login/';
var user = 'test35';
var pass = 'mypassword';
// Save these for future requests
var userId;
var authToken;
// Use POST instead of GET
request.post(
{
uri: url,
// I'm using form because it matches the urlEncoding behaviour expected by `restivus`
form: { username: user, password: pass }
},
function(err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
}
var json = JSON.parse(body);
authToken = json.data.authToken;
userId = json.data.userId;
console.log('Post successful! Server responded with:', body);
// And now we make the second request
// Welcome to callback hell
var articlesUrl = 'http://localhost:3000/api/v1/articles/';
request.get({
uri: articlesUrl,
headers: {
'X-User-Id': userId,
'X-Auth-Token': authToken
}
}, function(err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
}
console.log('Get successful! Server responded with:', body);
});
}
);

How to configure API endpoint to receive file from ember-uploader component

I'm trying to figure out how to use ember-uploader, I have the following component (like the one in the README)
export default EmberUploader.FileField.extend({
filesDidChange: function(files) {
const uploader = EmberUploader.Uploader.create({
url: (ENV.APP.API_HOST || '') + '/api/v1/images/',
});
console.log(uploader);
if (!Ember.isEmpty(files)) {
var photo = files[0];
console.log(photo);
uploader.upload(photo)
.then(data => {
// Handle success
console.log("Success uploading file");
console.log(data);
}, error => {
// Handle failure
console.log("ERROR uploading file");
console.log(error);
});
}
}
});
The express API endpoint is listening for a POST request.
var saveImage = (req, res, next) => {
let body = req.body;
res.json({
data: body
});
};
But the body is empty after the request is done. I really don't know how to implement the API endpoint in order to get the file, I tried to see the req object and it doesn't contains the file.
Debugging it, After select a file using the component I get the following info in the console.
Seems that the API endpoint works because I get the following output:
POST /api/v1/images/ 200 27.284 ms - 11
But I can't get the file.
SOLUTION
In Express 4, req.files is no longer available on the req object by
default. To access uploaded files on the req.files object, use a
multipart-handling middleware like busboy, multer, formidable,
multiparty, connect-multiparty, or pez.
Following this blog, the code below was added to the API and the ember-uploader code posted in the question worked as expected.
import formidable from 'formidable';
var saveImage = (req, res, next) => {
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin', function (name, file){
file.path = __dirname + '/tmp/' + file.name;
});
form.on('file', function (name, file){
res.json({
data: file.name
});
});
};

Retrieving metrics through librado using NodeJS

Good morning!
I'm having troubles trying to get a single number from librato to use in a html page.
I just want to get the last value of the metric AWS.Billing.EstimatedCharges.total, the name of the client that spent that value and put it all together in a HTML page (simple, but not to me)
I'm trying to use this API https://github.com/goodeggs/librato-node
And I still not figured out how to solve this problem.
ps: I cannot use the embed chart.
var http = require('http');
http.createServer(function (req, res) { }).listen(1337, "127.0.0.1");
console.log('Server running at 127.0.0.1:1337/');
var librato = require('librato-node');
api = librato.configure({email: 'myemail', token: 'mytoken'});
librato.start(); process.once('SIGINT', function() { librato.stop();
// stop optionally takes a callback });
// Don't forget to specify an error handler, otherwise errors will be thrown
librato.on('error', function(err) { console.error(err); });
Try npm install librato-metrics, there's a lot of guessing here so please report back }8*)
const client = require('librato-metrics').createClient(
{
email: process.env.LIBRATO_METRICS_EMAIL,
token: process.env.LIBRATO_METRICS_TOKEN
}
const payload = {
count: 1,
resolution: 60
};
client.get('/metrics/AWS.Billing.EstimatedCharges.total', payload,
function(err, response) {
if (err) {
console.error(err, payload);
} else {
console.log(response);
}
});
```

Javascript scraper logging in

I seem to be doing something wrong.
I have a student website that I want to scrape, but first I need to log in. Currently I have a python scraper that does it. The website logs in with a post request to a url containing a sid and PIN.
var login_url = 'https://example.com';
var formData = {
sid: 'username',
PIN: 'password'
}
How would I go about creating the same scraper but with javascript? I have seen the request library, which seems like what I want to use but cannot get it to work.
You need to use the request module to POST the form data to your endpoint. The response from the server will be in the call back to the .post() method.
const request = require('request');
// do not reassign "request", if you need to set properties us a different variable
// use the action= value from the form for the URL
const url = 'https://central.carleton.ca/prod/twbkwbis.P_ValLoginn';
const data = {
sid: 'username',
PIN: 'password',
};
request.post({ url: url, formData: data }, (err, response, body) => {
if (err) {
console.log('failed', err);
} else {
console.log('the response', body);
}
});
If you are interesting in parsing the resulting HTML I recommend using CheerioJS - much like jQuery but server side.

Categories