POST method through node.js - javascript

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

Related

Nextjs - Requesting Spotify Access Token - unsupported_grant_type [duplicate]

I'm working on integrating spotify and I'm making my own api. I can't understand why my request is not working. It works fine in python but not when I use express.
I get this response body :
{"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}
Express :
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var fetch = require('node-fetch');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.listen(80);
app.post('/v1/spotify/api/token', function(req, res) {
let body = req.body
let redirect_uri = body.redirect_uri
let code = body.code
let data = {
grant_type:'authorization_code',
redirect_uri:redirect_uri,
code:code
}
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Authorization':'Basic *client_id:client_secret*',
'Content-Type':'application/x-www-form-urlencoded'
},
body: JSON.stringify(data)
}).then(r => r.json().then(data => res.send(data)))
});
Python:
r = requests.post("https://accounts.spotify.com/api/token",
data={
"grant_type":"authorization_code",
"redirect_uri":*redirect_uri*,
"code":*code*
},
headers = {
"Authorization": "Basic *client_id:client_secret*",
'Content-Type':'application/x-www-form-urlencoded'}
)
In your script of Node.js, data is sent as a string value. So how about this modification?
Modified script
Please modify the object of data as follows and try again.
// Below script was added.
const {URLSearchParams} = require('url');
const data = new URLSearchParams();
data.append("grant_type", "authorization_code");
data.append("redirect_uri", redirect_uri);
data.append("code", code);
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Authorization':'Basic *client_id:client_secret*',
'Content-Type':'application/x-www-form-urlencoded'
},
body: data // Modified
}).then(r => r.json().then(data => res.send(data)))
Reference:
Post with form parameters of node-fetch
If this didn't work, I apologize.
I had to put the client_id and client_secret in the body and not in Authorization header.
try {
const body = {
grant_type: "client_credentials",
client_id: <YOUR_ID>,
client_secret: <YOUR_SECRET>,
};
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams(body),
});
console.log({ response });
} catch (err) {
console.log({ err });
}

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

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

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