Get token oAuth using npm - javascript

I'm trying to develop a service using nodeJS that retrieve a token OAuth from a server. But I have every time an error.
this the function.
var express = require('express')
var http = require('http');
var httpRequest = require('request');
var bodyParser = require('body-parser');
var app = express()
app.get('/get-token', function (request, response) {
// Ask for token
httpRequest({
url: 'https://my-server.com/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic SdfdhffhPeHVBTV84OExfVWFmR1cwMklh'
},
form: {
'grant_type': 'password',
'username': 'myLogin',
'password': 'myPwd',
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
});
When I make a request, the server return this error:
{ [Error: unable to verify the first certificate] code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' }
Would you have an idea how I can process or if there is a package npm that make the same job ?
Best regards

This wokrks for me
...
app.get('/get-token', function (request, response) {
// Ask for token
httpRequest({
rejectUnauthorized: false,
url: 'https://my-server.com/token',
...

Related

Add a logger to log information for response and request from a server (express and nodejs)

My server will post data to another server, is there any way that I can add logger and log the response and request data thanks
const request = require('request');
requestIotPlatform = function requestIotPlatform(req, res, next) {
var formData = JSON.stringify(req.body);
var form = {
data_in: formData
};
var uri = 'XXXXXXXXXXXXXXXXXXXXXX';
var headers = {
'Authorization': authBase64,
//'Content-Length': form.length,
'Content-Type': 'application/x-www-form-urlencoded',
'Connection': 'keep-alive',
'charset': 'utf-8'
};
request.post({
headers: headers,
uri: uri,
form: form
}, function (err, response, body) {
console.log(response.statusCode)
});
next();
}
module.exports = { requestIotPlatform };
I use this module, basically it's a middleware for logging request/responses in Express apps: https://www.npmjs.com/package/express-requests-logger

Unable to receive response inspite of giving right API key in node js post request

Please help me with the below POST request that I'm trying to make. Below is the code snippet.
const express = require("express");
const bodyParser = require("body-parser");
//const request = require("request");
const https = require("https");
const request = require('request-promise');
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.get("/", function(req, res){
res.sendFile(__dirname + "/test.html");
});
const data = {
"some_header":{
"name":"xxxxx"
}
};
const jsonData = JSON.stringify(data);
console.log(jsonData);
app.post("/post", function(req, res){
const url = "xxxxxxxxxxxx";
const options = {
method: "POST",
body: data,
json: true,
headers: {
ContentType: "application/json",
Authorization: "nhgjgjhgjghjghj"
}
}
const request = https.request(url, options, function(response) {
if (response.statusCode === 200) {
// res.send("success");
console.log("success");
} else {
//res.send("Failed");
console.log("failure");
}
response.on("data", function(data) {
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
});
app.listen(process.env.PORT || 3000, function() {
console.log("The app is up and running on Port 3000");
});
I'm getting 200OK response from the external server, but unable to post the data. When I logged the response data from the server, I received this success
{ require_login: true }
"Success" is the console log message. require_login: true is the response I'm getting from the server. where am I going wrong?
Try to add Basic before you api key. Also, if you are using base64, then check that original string is right one and should be something like: login:password
headers: {
ContentType: "application/json",
Authorization: "Basic BAsE64Format or api:key or login:password"
}
headers: { "Content-type": "application/json", Authorization: 'Basic ' + Buffer.from('CtB2HZwaRdGggr1g4K').toString('base64') }
enclosing the content-type with quotes and converting the API key to base 64 did the trick

POST method through node.js

I am writing a simple node.js for a REST API call to create object through POST method and get the response code. But while running the script I get "0 passing" .
Here is my code:
var request = require("request");
var options = { method: 'POST',
url: 'https://example.org',
headers:
{ 'content-type': 'application/vnd.nativ.mio.v1+json',
authorization: 'Basic hashedTokenHere' },
//body: '{\n\n"name": "My JS TEST",\n"type": "media-asset"\n\n}'
};
request(options, function (error, response, body) {
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
Can anyone help to to run it successfully and get the response code?
Thanks!
I calling my local API hope this will make thing get clear. It's work for me
This my API
var express = require('express')
var router = express.Router()
var bodyParser = require('body-parser');
var app=express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/api',function(req,res)
{
res.status(200).send(req.body.name+"hi");
})
app.listen(8080,function(){
console.log("start");
})
Now, through Request, i will request this post method
var request = require('request');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-type': 'application/json',
'Authorization': 'Basic ' + auth,
}
var postData = {
name: 'test',
value: 'test'
}
// Configure the request
var options = {
url: 'http://127.0.0.1:8080/api',
method: 'POST',
json: true,
headers: headers,
body: postData
}
// Start the request
request(options, function (error, response, body) {
// Print out the response body and head
console.log("body = "+body+" head= "+response.statusCode)
}
})

How to pass json to nodejs request post method?

I try to pass json to nodejs post method.But i'm getting error "The search query must be specified.". I have specified search string and filter the code. Can you advise what cause this error.
Same request working in POSTMAN.
//Load the request module
var express = require('express');
var request = require('request');
var app = express();
//Lets configure and request
request({
url: 'http://host:8080/rest/1.0/search',
qs: {query: 'nodejs*'},
method: 'POST',
json: {
filter:
{
community: ['33862a97-44e5-4de5-9206-db0a61dd83ca'],
vocabulary: ['b80f3576-0642-4049-bb07-d72a0dd9e3e0','48029bb8-0585-4ed5-afaa-55014aebfcb3'],
type: {asset:['00000000-0000-0000-0000-000000011001']},
},
fields: ['name']
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
app.listen(8080);
As per your postman screenshot you can try the below code by getting rid of qs: {query: 'nodejs*'} and adding the same inside the json.
//Load the request module
var express = require('express');
var request = require('request');
var app = express();
//Lets configure and request
request({
url: 'http://host:8080/rest/1.0/search',
method: 'POST',
json: {
query: 'nodejs*',
filter:
{
community: ['33862a97-44e5-4de5-9206-db0a61dd83ca'],
vocabulary: ['b80f3576-0642-4049-bb07-d72a0dd9e3e0','48029bb8-0585-4ed5-afaa-55014aebfcb3'],
type: {asset:['00000000-0000-0000-0000-000000011001']},
},
fields: ['name']
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
app.listen(8080);

HTTP post header is incorrect

I am using node.js to send HTTP POST to an APP server. The email address joe#gmail.com in POST body shows up as joe%40gmail.com on APP server side. I used Content-Type text/plain in the following code but application/x-www-form-urlencoded is actually in the POST request header, according to the server log.
My earlier post has a mistake on Chrome postman results. Please ignore it, and sorry for the confusion.
I am new to this, and may have missed something obvious here. Any help is appreciated.
Here is the code:
var express = require("express");
var app = module.exports = express();
var request = require('request');
var config = require('../config');
app.post('/', function(req, res) {
var username = req.body.name;
var password = req.body.passwd;
var email = req.body.email;
console.log("email=", email);
// connect to APP server
var url = config.appServer;
request( {
uri: url,
method: "POST",
timeout: 10000, // 10 sec
headers: {
'Content-Type': 'text/plain'
},
form: {
act: 'create',
username : username,
passwd: password,
email: email
}
}, function (error, response, body) {
// handle return here
That's completely normal behavior. Also you don't need to set the content-type header when using the form option with request.
Here is a short example:
request({
uri: 'http://requestb.in/1g2xzno1',
method: 'POST',
timeout: 10000, // 10 sec
form: {
act: 'create',
username : 'username',
passwd: 'password',
email: 'joe#gmail.com'
}
}, function (err, res, body) {
if (err) console.log(err)
console.log(body)
})
You can see the results from that request here. This is what your app server receives. Then all you need to do is parse the request body on your app server (it's the string below the RAW BODY header):
var qs = require('qs')
qs.parse('act=create&username=username&passwd=password&email=joe%40gmail.com')
{ act: 'create',
username: 'username',
passwd: 'password',
email: 'joe#gmail.com' }
Alternatively if you are using Express on your app server you can use the body-parser middleware that will do the same for you:
app.use(bodyParser.urlencoded({extended: true}))

Categories