Axios is not working to get access token? - javascript

i have axios call to get the bearer token it is oauth2.0 but for some reason it is failing same call is working in postman.
index.js
export async function getESLAccessToken(apiConfig: any) {
const _body = {
grant_type: apiConfig.authOptions.body.grant_type,
client_id: apiConfig.authOptions.credentials.sdk_voyage.clientId,
client_secret: apiConfig.authOptions.credentials.sdk_voyage.clientSecret,
scope: apiConfig.authOptions.body.scope
};
const _headers = {
"Content-Type": "application/x-www-form-urlencoded",
"appName": "Blink",
"Accept": "*/*",
"Content-Length": 163
};
const request = {
method: 'POST',
_body,
headers: _headers
};
try {
const resp = await axios.post('https://auth/oauth2/token',
request);
console.log(resp.data);
} catch (err) {
// Handle Error Here
throw err;
}
}
This is how request building for axios
{
"method": "POST",
"_body": {
"grant_type": "client_credentials",
"client_id": "abc",
"client_secret": "xyz",
"scope": "APPPII APPPHI"
},
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"appName": "Blink",
"Accept": "*/*",
"Content-Length": 163
}
}
Error
Error: Request failed with status code 400
Postman working request and response
POST https://auth/oauth2/token
200
163 ms
POST /auth/oauth2/token HTTP/1.1
Headers
User-Agent: PostmanRuntime/7.26.8
Accept: */*
Cache-Control: no-cache
Postman-Token: d90ccc33-1d77-4502-9a41-74080dd3d7a5
Host: qaapih8.corp.cvscaremark.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 163
Request Body
grant_type=client_credentials&client_id=abc&client_secret=xyz&scope=APPPII%20APPPHI
HTTP/1.1 200 OK
Response Body
{ "token_type":"Bearer", "access_token":"token returned", "expires_in":3600, "consented_on":164684, "scope":"APPPII APPPHI" }

The second argument of the axios.post function should be the request body. And the third argument should be the Axios request config object (Which you can set your headers). Axios POST Requests
In your case, the code should be like:
const body = {
grant_type: apiConfig.authOptions.body.grant_type,
client_id: apiConfig.authOptions.credentials.sdk_voyage.clientId,
client_secret: apiConfig.authOptions.credentials.sdk_voyage.clientSecret,
scope: apiConfig.authOptions.body.scope
};
const myHeaders = {
// add your headers here
}
const response = await axios.post(
'https://auth/oauth2/token',
body,
{ headers: myHeaders }
);

Replace
const request = {
method: 'POST',
_body,
headers: _headers
};
with:
const request = {
method: 'POST',
data: _body,
headers: _headers
};
As pointed out by the docs in the comments session: https://axios-http.com/docs/req_config

Related

how can I send an image binary via post to an API? nodejs

I am getting the image binary like this:
axios.get("image-url.jpg")
I need to use the response for making a new POST request to another server
const form = new FormData();
const url = "post-url-here.com";
form.append(
"file",
new ReadableStream(Buffer.from(file)),
"image-test.jpg"
);
const config = {
headers: {
...form.getHeaders(),
Authorization:
"Bearer token-here",
},
};
axios.post(url, form, config);
Unfortunately that isn't working. The response I am getting is:
data: {
message: 'This file is not compatible with the picture engine, please try another one',
error: 'bad_request',
status: 400,
cause: []
}
How can I properly do that ?
edit:
form.getheaders is adding this headeer to the request:
'content-type': 'multipart/form-data; boundary=--------------------------783115116498484087556627'
all request headers:
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'multipart/form-data; boundary=--------------------------918731250556909112992344',
Authorization: 'Bearer token-here',
'User-Agent': 'axios/0.21.1'
},
all request information:
_header: 'POST /pictures/items/upload HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: multipart/form-data; boundary=--------------------------116660171215340291632150\r\n' +
'Authorization: Bearer token-here\r\n' +
'User-Agent: axios/0.21.1\r\n' +
'Host: api.mercadolibre.com\r\n' +
'Connection: close\r\n' +
'Transfer-Encoding: chunked\r\n' +
'\r\n',
An example of POST Header:
POST /video-upload/ HTTP/1.1
Host: your host
User-Agent: axios/0.21.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=---------------------------219493771727403213993181042749
Content-Length: 99211703
Connection: keep-alive
as you can see there are important parts like:
POST /the-url/ HTTP/1.1
Host: your host
Content-Length: the length in bytes of your image
Content-Type: multipart/form-data; boundary=---------------------------219493771727403213993181042749
Connection: keep-alive
So your script do not read the images , your header is broken as status:400 response from Server says.
Try this (pseudo code) :
const axios = require('axios');
const fs = require('fs');
var im_config = {
responseType: 'stream'
};
let im_url = 'image-url' ;
async function getImage() {
let resp = await axios.get(im_url, im_config);
//save the image
resp.data.pipe(fs.createWriteStream('test-image.jpg'));
}
getImage().then(function(result){
console.log(result);
const form = new FormData();
const url = "server url where send the form ";
// interesting part
form.append('image', 'test-image.jpg');
axios.post(url, form, your-config);
});
It worked! Ok.
To do it on the fly , try to abtain a refer to the downloaded image from 'result' or 'resp' without saving the image.
Otherwise unlink downloaded image after POST is done.
fs.unlink('test-image.jpg', (err) => {
if (err) {
console.error(err)
return
}
}

Response keep return Status code 403 instead of 200

I am trying to get Status 200 response from my request, but keep receiving 403
const request = require('request');
const cheerio = require('cheerio');
let options = {
url: 'https://www.norwegian.com/en',
headers: {
"Cache-Control": "max-age=0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.5",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0",
}
};
request(options, function (err, resp, html) {
if (!err) {
const gatherInformation = cheerio.load(html);
console.log(resp.statusCode);
}
})
My request header according Firefox dev tools:

500 error on .net core web api post using fetch

I am using the javascript fetch api https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
with a .net core 3 web api.
the controller returns OK(object) but the fetch receives a 500 status code.
here is the controller. I can step through the code and see that it is returning Ok(customer)
[HttpPost]
public async Task<IActionResult> PostCustomerAsync([FromBody] Customers customer)
{
await _customersService.AddAsync(customer);
return Ok(customer);
}
}
here is the fetch.
fetch("./api/customers",
{
method: "POST", body: JSON.stringify(data),
headers: {
'Accept': 'text json',
'Content-Type': 'application/json'
},
})
.then(function(response, error){
console.log(error);
console.log(response);
if(!response.ok){
console.log(response);
throw Error(response.statusText);
}
return response;
}).then(function(response){
Toastr.success(`${data.firstname} ${data.lastname} has been successfully registered`);
const bookChapterTable = new BookChapterTable();
}).catch(function(error){
console.log(error);
Toastr.error(`An error occured : ${error}`);
})
}
the fetch is stopping at !response.ok
here is response.
body: ReadableStream
locked: false
__proto__: ReadableStream
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 500
statusText: ""
type: "basic"
url: "https://localhost:44300/api/customers"
from network tab
Request URL: https://localhost:44300/api/customers
Request Method: POST
Status Code: 500
Remote Address: [::1]:44300
Referrer Policy: no-referrer-when-downgrade
date: Thu, 31 Oct 2019 18:34:14 GMT
server: Microsoft-IIS/10.0
status: 500
x-powered-by: ASP.NET
:authority: localhost:44300
:method: POST
:path: /api/customers
:scheme: https
accept: text json
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
content-length: 171
I have same problem. Error shown because I was't sending 'X-XSRF-Token' at header (it can be 'X-CSRF-TOKEN' depends from system). If anyone has same problem make sure you pass it at header.
fetch(signUpEmailUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-XSRF-Token': gettoken()
},
credentials: 'include',
body: JSON.stringify({
email: $('#sign_up_email').val(),
firstName: $('#first_name').val(),
lastName: $('#last_name').val(),
token: $('#sign_up_token').val()
})
})
.then(res => (res.json()))
.then(data => {
console.log(data);
loginSuccess(data);
})
.catch(err => {
console.log(err);
});
`

CoffeeScript: HTTPS Post to API, handle response

I'm new to CoffeeScript/JavaScript, but writing a script for Hubot to talk to my Ansible Tower API in Coffee. Below is my code so far:
module.exports = (robot) ->
robot.respond /deploy zabbix agent (.*)/i, (res) ->
host = res.match[1]
https = require 'https'
authbody = JSON.stringify({
username: "awx.api",
password: "example"
})
authrequest = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/authtoken/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
})
authrequest.end(authbody)
body = JSON.stringify({
limit: "#{host}"
})
request = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/job_templates/35/launch/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
})
request.end(body)
res.reply "Deploying zabbix agent to #{host}"
In the authrequest section, I post my username and password to the API and it should return in the response JSON in the following format:
{
"token": "8f17825cf08a7efea124f2638f3896f6637f8745",
"expires": "2013-09-05T21:46:35.729Z"
}
My questions is how I store the token to use as my authentication in the later requests.
You can store it in localStorage like so:
localStorage.setItem("token", "8f17825cf08a7efea124f2638f3896f6637f8745",);
and the get it when you make a request and insert in your header
const token = JSON.parse(localStorage.getItem('token'));
request = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/job_templates/35/launch/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body),
'Authorization': 'Bearer ' + token
}
})
request.on('response', function (response) {
response.on('data', function (chunk) {
let json = JSON.parse(chunk);
localStorage.setItem("token", json['token']);
});
});

How to decode the NodeJs HTTPS request, which is returning an encoded blob?

I made a POST request to a server and got this back:
toJSON: [Function: responseToJSON],
caseless:
Caseless {
dict:
{ server: 'Apache-Coyote/1.1',
pragma: 'no-cache',
'cache-control': 'no-store',
'content-encoding': 'gzip',
'content-type': 'application/json;charset=UTF-8',
'content-length': '287',
date: 'Fri, 23 Jun 2017 14:06:47 GMT',
connection: 'close' } },
read: [Function],
body: '\u001f?\b\u0000\u0000\u0000\u0000\u0000\u0000\u0000???j\u0003!\u0014???
?C\u0018??\u0017\u001cG\u001d?k???????L\u0018\r$-}??t?]?v???|???z??4H?9\u000fe:?
??6?X\u0013Zv`?cP\u001c\u0005X?\u0011?\f\u001amKd?m?\u001f?C\u0019????;!-?o?4s\u
001eR???\u0010_t?X????B?\u0018\u001ch?\u001eTo%?3\u0016?tJ?\u000e^j?\u0014f?\u00
1e\u0013??\u0017R?\u0003?+???*{\u0017A???l\u000fd\b??,\u001b\u0015~Hx|??T?SU?\n
?\b?\u0012?k\u0019??+???sA*C\n5??\u0010V?\u001a??c?sY\u001ec$?AH\u000b2?\u0001??
\u0005??\u0015D?\u001db\'HZ??&_cL???$?~W?⌂?>??p????????\u0003z$B??\u0001\u0000\u
0000' }
Now I know whatever is in the encoded "body" is what I am looking for, because when I do this post request on Fiddler, It follows the same format, except the body is JSON code. Is there a way to decode this?
Edit:
var options = {
url: someURL,
host: "SomeApi.com",
method: 'POST',
headers: {
'Accept': 'application/json, text/json, text/x-json, text/javascript, text/xml, application/xml',
'User-Agent': 'RestSharp/105.2.3.0',
'Accept-Encoding': 'gzip, deflate',
'Content-Length': '0'
},
}
request(options, function (error, response, body) {
console.log(response)
})

Categories