I can't seem to get a proper response using the request package with node. I have tried several different placements according to the documentation on npm but keep getting the same result.
"Invalid Access Token
401"
I've asked around the forums and they ensure me that the token I'm using is correct. Any help would be greatly appreciated!
const restify = require('restify');
const request = require('request');
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log('%s listening to %s', server.name, server.url);
});
var options = {
url: 'https://css.api.hp.com/productWarranty/v1/queries',
json: true,
method: 'POST',
Authorization: 'Bearer MYAUTHORIZATIONKEY',
headers: {
'Content-Type': 'application/json',
'Accept': 'text/plain',
}
};
var callback = (error, response, body) => {
console.log(body);
console.log(response.statusCode);
}
request(options, callback);
the authorization element should be in the headers object. Like this:
var options = {
url: '<your url>',
method: 'POST',
json: requestBody,
headers: {
'User-Agent': 'my request',
'Authorization': 'Bearer <your token>',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
Please give that a try.
Related
How do you correctly set authorization header in a Https library in NodeJS.
I am doing the following:
const https = require('https');
...
const optionsCFS = {
hostname: process.env.CLOUD_URL,
port: 443,
timeout: 5000,
path: process.env.CLOUD_ORDER_SAVE_PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': (new TextEncoder().encode(CFSdata)).length,//CFSdata.length,
'Authorization': `bearer ${token}`, // ?
}
}
I am getting a 401 error from the Cloud Function side.
It works with node-fetch library and I use the following format for it:
headers: {
'Content-Type': 'application/json',
Authorization: `bearer ${token}`},
});
You get 401 if you're using an incorrect ID token. First, make sure that your user (or service) account has Cloud Functions Invoker role on IAM.
Then, generate your ID token by running this command:
gcloud auth print-identity-token
I'm using this sample code to call my Cloud Function which accepts POST requests and it works just fine:
var https = require('https');
function postCode() {
var payload = '{"name":"donnald"}';
const token = 'eyJhbxxxxx';
var post_options = {
host: '[REGION]-[PROJECT_ID].cloudfunctions.net',
path: '/func-post',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
'Authorization': `Bearer ${token}`
}
};
var post_req = https.request(post_options, res => {
res.setEncoding('utf8');
res.on('data', chunk => {
console.log('Response: ' + chunk);
});
});
post_req.write(payload);
post_req.end();
}
postCode()
I have been trying to do a GET request to my server which has is running locally on port 4000.
I generate a JWT token and pass it in the header as follows
var request = require('request');
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'JWT': '<JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
But I keep getting
{"errors":[{"title":"invalid_request","id":"Requesting stuff","meta":{"server-time":1591980353},"errorCode":"bad-request","status":400,"detail":"This JWT has invalid path parameter"}],"error_description":"This JWT has invalid path parameter","error":"invalid_request"}
My JWT is correctly created, I verified it in https://jwt.io/
Is it because 'request' module is deprecated in node.js?
Is there another way I can achieve the below?
Try this one
var request = require('request');
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'Authorization': 'Bearer <JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
or
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'Authorization': 'JWT <JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
Bearer or JWT depends how it is defined in backend
I have to call an api, for which we are using request library.
const options = {
uri: 'https://abcd.com',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer xxxxxxxxx'
},
form: {
'a':1,
'b':2
}
}
request(options, (e, res, data) => {});
How would I rewrite the same using node's https library.
I tried using https library's https.request() with 'POST' type and .write with form object. Didn't work.
Also changed Content-Type to application/x-www-form-urlencoded, didn't work either
This example is from the documentation using the request package ,the form takes a object consisting of key value pair from that of the form
request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}},
function(err,httpResponse,body){ /* ... */ })
enter link description here
You can read the API docs at: https://nodejs.org/api/https.html
Below code should work fine:
const https = require('https')
const data = JSON.stringify({
'a':1,
'b':2
})
const options = {
hostname: 'example.com',
port: 443,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
'Content-Length': data.length
'Authorization': 'Bearer xxxxxxxxx'
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
I am having an issue when send Http request to Infobip SMS APi with Unicode character in body. I tried with axios and request module but both are not working for unicode value but it's working for normal english character. here is the code
var express = require('express');
var request = require('request');
var app = express();
var url = 'http://api.infobip.com/sms/2/text/single'
var options = {
method: 'post',
data: {
'from': 'ME',
'to': '(555) 555-1234',
'text': 'ওহে বিশ্ব',
},
headers: {
'authorization': 'Basic AUTH_KEY',
'content-type': 'application/json',
'accept': 'application/json'
},
url: url
}
request(options, function (err, res, body) {
if (err) {
console.log('Error', err);
}
console.log(res, body);
})
you can check it by axios
var express = require('express');
var app = express();
var axios = require("axios");
const config =
{
headers:
{
'authorization': 'Basic AUTH_ID',
'content-type': 'application/json;charset=UTF-8',
'accept': 'application/json'
}
};
axios.post('http://api.infobip.com/sms/2/text/single',
{
'from': 'ME',
'to': '+8801XXXXXX',
'text': 'ওহে বিশ্ব',
},
config,
)
.then(function(response) {
console.log(response.data)
})
.catch(function(error) {
console.log(error)
})
How can we use bearer token with POST method using npm sync-request? The sync-request resource page has the way to use authorization in GET request but not in POST request.
*******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent'
}
});
****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
json: { username: 'Name' }
});
Not sure why you would want to use sync-request which can cause timing issues but this should work with either sync-request or request
// *******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent',
'authorization', 'Bearer ' + authId
}
});
// ****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
'headers': {
'authorization', 'Bearer ' + authId
},
json: { username: 'Name' }
});
authId needs to be whatever your bearer token spoils be for your app.
I would suggest use of axis and example below:-
GET
import axios from "axios";
axios({
method: 'get',
url: url,
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
}).catch((err) => {
console.log(err)
));
POST
axios({
method: 'post',
url: url,
data: JSON.stringify({orders}),
headers: {
'Content-Type': 'application/json',
'Authorization': userObj.token
}
}).then(function (response) {
console.log(response)
});
Where ubserObj.token -
Bearer Token ex: Bearer ASDF#!##!ADFASDF!##!##
This will be on the server side settings.