How to pass json to nodejs request post method? - javascript

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

Related

Get token oAuth using npm

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',
...

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

Unexpected token - while parsing json request

I have two node servers and I am trying to send files between them using a rest api. However when I am sending the data I get a "Unexpected token -"on the receiving server. On the sender I get an [Error: write after end].
My router code:
var express = require('express');
var multer = require('multer');
var path = require('path');
var Router = express.Router;
const MODULES_PACKAGES_UPLOAD_DIR = path.resolve('/tmp');
module.exports = function() {
var router = new Router();
var storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, MODULES_PACKAGES_UPLOAD_DIR);
}
});
var upload = multer({storage: storage});
router.post('/fileUpload', upload.array(), function(req, res){
debug('We have a a file');
//Send the ok response
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('\n');
}
The sending code:
var Util = require('util');
var http = require('request-promise');
var request = require('request');
var fs = require('fs');
var Post = require('http');
var FormData = require('form-data');
//Generate the form data
var formdata = modules.map(function(fileName){
return fs.createReadStream('/opt/files/'+fileName);
});
var data = getData(); //Gets the body of the code as a promise
return Promise.all(data)
.then(function(dataResults){
var options = {
method: 'POST',
uri: 'https://' + name +'/file',
rejectUnauthorized: false,
timeout: 2000,
body: {
keys: keyResults,
modules: modules,
},
formData: { <====== If I remove this section everything works
'module-package': formdata,
},
json: true // Automatically stringifies the body to JSON
};
request.post(options, function(err, response){
if( err){
debug('Error: ',err);
}
else{
debug('We posted');
}
});
The weird thing is that if I remove the formData section then everything works but when it is there I get an exception that says:
SyntaxError: Unexpected token -
at parse (/home/.../projects/node_modules/body-parser/lib/types/json.js:83:15)
Does anyone have any idea what I could be doing wrong??
Just in case anyone in the future comes with the same problem. As #Bergi mentioned. You cant have both json data and form data. You need to choose either one. The solution is to just pass the json data as apart of the form like.
var options = {
method: 'POST',
uri: 'https://' + name +'/file',
rejectUnauthorized: false,
timeout: 2000,
body: {
},
formData: {
'module-package': formdata,
keys: keyResults,
modules: modules,
},
json: true // Automatically stringifies the body to JSON
};
request.post(options, function(err, response){
if( err){
debug('Error: ',err);
}
else{
debug('We posted');
}
});
In my case, the header of the HTTP Request contained "Content-Type" as "application/json".
So here are the things to check:
Send only either form-data or json body. NOT BOTH.
Check for Headers if the "Content-Type" is mentioned. Remove that.

Getting 500 error from API request for my node.js express app

I have a custom module that sends a API request and receives JSON.
data.js
var data = function(callback) {
var request = require('request')
request.post('https://getpocket.com/v3/get', {
headers: {'content-type':'application/json'},
body: JSON.stringify({
consumer_key:'...',
access_token:'...',
tag: 'nodejs'
})
}, function (err, res, body) {
callback(body);
})
}
module.exports = data;
And the route that will render the data.
index.js
var express = require('express');
var router = express.Router();
var data = require('../lib/data.js');
router.get('/', function(req, res, next) {
data( function(data) {
console.log(data)
res.render('index', {
title: 'Express',
body: data
});
});
});
module.exports = router;
With this structure I always get GET / 500 1129.898 ms - 1725
If I place the API request implementation in app.js like the following, I'm getting the data without 500 error.
app.js
var request = require('request')
request.post('https://getpocket.com/v3/get', {
headers: {'content-type':'application/json'},
body: JSON.stringify({
consumer_key:'...',
access_token:'...',
tag: 'nodejs'
})
}, function (err, res, body) {
//callback body
})
But having this in app.js, I'm not sure how to pass the data to the route index.js and make the callback work and also not sure if app.js is the right place for this implementation so I'm hoping to make my custom module data.js work but what can possibly cause 500 error?

How to extract data from XML using node.js

how to extract data from XML type rest API using node.js?
This is the code i used to get data by sending rest api request:
//Load the request module
var request = require('request');
//Lets configure and request
request(
{
url: 'http://nemo.sonarqube.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverage', //URL to hit
method: 'GET', //Specify the method
headers: { //We can define headers too
'Authorization': 'Basic ' + new Buffer( 'admin' + ':'+'admin').toString('base64'),
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
},
function(error, response, body){
if(error) {
console.log(error);
} else {
var obj=JSON.parse(response.body);
console.log(obj.id);
}
}
)
var express = require('express');
var app = express();
var server = app.listen(3000,function (){
console.log('port 3000');
}
);
When I send the request using a browser, the result appears like:
<resources>
<resource>
<id>400009</id>
<key>DEV:Fabrice Bellingard:org.codehaus.sonar:sonar</key>
<name>SonarQube</name>
<lname>SonarQube</lname>
<scope>PRJ</scope>
<qualifier>DEV_PRJ</qualifier>
<date>2015-08-04T13:10:57+0000</date>
<creationDate/>
<copy>48569</copy>
<msr>
<key>ncloc</key>
<val>879.0</val>
<frmt_val>879</frmt_val>
</msr>
<msr>
<key>coverage</key>
<val>81.8</val>
<frmt_val>81.8%</frmt_val>
</msr>
</resource>
</resources>
I want to extract the id and print it on the console using node.js.
How I want to edit the above code?
The problem is response.body is in array format, so get the first item in the array and then its id value
//Load the request module
var request = require('request');
//Lets configure and request
request({
url: 'http://nemo.sonarqube.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverage', //URL to hit
method: 'GET', //Specify the method
headers: { //We can define headers too
'Authorization': 'Basic ' + new Buffer('admin' + ':' + 'admin').toString('base64'),
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
}, function (error, response, body) {
if (error) {
console.log(error);
} else {
var arr = JSON.parse(response.body);
var obj = arr[0];
console.log(obj.id);
}
})
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
console.log('port 3000');;
});

Categories