How to use the basic authentication in NestJS? - get

So I'm trying to do an API call, and I have to use basic authentication.
The codes are like these :
const headersRequest = {
'Content-Type' : 'application/json',
'Authorization' : `Basic ${this.authToken}`
}
let response = this.httpService.get(url, {headers: headersRequest});
The question is the above get() function call correct?
Because the output of :
console.log(response)
is :
Observable { _isScalar: false, _subscribe: [Function (anonymous)] }
and not the response object which I wanted.
I have tried to explore HttpService get, but couldn't find any detailed documentation related to this basic authentication.
PS: I'm a PHP developer and just learned NestJS in the last couple of days.

The easiest way to get the proper result from the observable is to to just convert it to a promise in this case.
const response = await this.httpService.get(url, {headers: headersRequest}).toPromise()

Related

Body of a request is empty [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

Can't upload file with Multer, React Native and Axios

I know there are thousands of questions like this, but none of the solutions works for me:
Change to Fetch Api
Use format {uri: ..., type: ..., name: ...} in formData
I also have noticed that I can't send the formData directly in the "data" axios's property (when using Axios({...})), because the formData object has a property call "._parts", so I have to do:
let formData = new FormData()
formData('image', {uri: imagePicker.uri, name: 'some_name.jpeg', type: 'image/jpeg'})
formData('data', {name: 'Andrea'})
let xmlHttp = await Axios({
method: 'POST',
url: `url...`,
data: formData._parts,
headers: {
Authorization: `Bearer ${_token}`,
'Content-Type': 'multipart/form-data',
},
} ).catch(error => {
throw error
});
Then, in Node, I get this:
req.body -> [Object: null prototype] {}
req.file -> undefined
upload.single("image"), in router.post and multerS3.
Some idea? Thank you
I had the same problem with Axios for 6 days :D , there is no problem with Multer i got.
but in the code you leave data should be formData not the formData._parts.
just check it if it doesnt solve your problem i strongly recommend you to use https://github.com/joltup/rn-fetch-blob ,because the Axios package has got some issues you can also check it from github issue.
for me Using the RNFetchBlob did the job i hope it helped

Getting 400 Bad Request When POSTing to Get Transaction Token

I'm trying to integrate our website with Converge API with Hosted Payments Page. Here is the link to their documentation https://developer.elavon.com/#/api/eb6e9106-0172-4305-bc5a-b3ebe832f823.rcosoomi/versions/5180a9f2-741b-439c-bced-5c84a822f39b.rcosoomi/documents?converge-integration-guide/book/integration_methods/../../book/integration_methods/hosted_payments.html
I'm having troubles getting past the first step which is requesting a transaction token from their API endpoint. I'm sending a POST request from my server using axios with the correct parameters and URL, but when I try and POST i get 400 Bad Request. When I make the same request in POSTMAN I get a 200 response with the transaction token. I talked to their developers and they said that everything I was doing was correct and that nothing seemed odd within my code, so even they were stumped as to why I couldn't make a POST request to their endpoint. Obviously there is something within my code that their API is not liking, or else I wouldn't be here trying to find answers for this.
Here is how I'm making the POST request:
app.get('/converge_token_req', (request, response) => {
let params = {
ssl_merchant_id: '*****',
ssl_user_id: '*****',
ssl_pin: '*****',
ssl_transaction_type: 'ccsale',
ssl_amount: '1.00'
}
axios.post('https://api.demo.convergepay.com/hosted-payments/transaction_token', params, {
headers: { 'Content_Type' : 'application/x-www-form-urlencoded' }
}).then((res) => {
response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token')
response.send(error.message)
})
})
Here are the Request Headers:
I'm honestly out of ideas to try. The developers say that everything looks just fine yet I'm unable to make a successful request to their API. If anyone has any thoughts on this that would be great. Thanks!
This code below worked for me:
app.get('/converge_token_req', (request, response) => {
let params = {
ssl_merchant_id: '*****',
ssl_user_id: '*****',
ssl_pin: '*****',
ssl_transaction_type: 'ccsale',
ssl_amount: '1.00'
}
axios({
method: 'post',
url: 'https://api.demo.convergepay.com/hosted-payments/transaction_token',
params: params
}).then((res) => { response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token: ',
error)
})
})
I've since found out the solution to my problem. The issue here is that converge expects a x-www-form-urlencoded string that needs to be Stringified before submitting the request. I found a library that works well for this called qs and I used it like so:
let params = qs.stringify({ // need this if content_type is application/x-www-form-urlencoded
ssl_merchant_id: env.CONVERGE.MERCHANT_ID,
ssl_user_id: env.CONVERGE.USER_ID,
ssl_pin: env.CONVERGE.PIN,
ssl_transaction_type: request.query.type,
ssl_amount: request.query.amount,
ssl_email: request.query.email,
ssl_company: request.query.company,
ssl_avs_address: request.query.address,
ssl_avs_zip: request.query.zip,
ssl_description: request.query.desc,
})
axios.post('https://api.convergepay.com/hosted-payments/transaction_token', params, {
headers: {
'Content_Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then((res) => {
response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token')
response.send(error.message)
})
I think you could also get away with just using JSON.stringify() but this way worked for me.

Access an API via Node.js

Using the sample Python code provided by the Bureau of Labor Statistics I was able to successfully access their API and print the JSON containing the data series in the console. Python code below:
#BLS query.
headers = {'Content-type': 'application/json'}
data = json.dumps({"seriesid": ['CES0000000001'],"startyear":"2010", "endyear":"2019"})
result = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data=data, headers=headers)
print(result.text)
While the Python code works just fine, I would prefer to use JS, but have been unsuccessful in doing so. I have tried using fetch, but I am not making any progress. See JS code below:
fetch('https://api.bls.gov/publicAPI/v2/timeseries/data/', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({seriesid: ['CES0000000001'], startyear:"2010", endyear:"2019"})
})
.then(function(response) {response.json()})
.then(function(json) {console.log(json)});
I am sure I am messing up something simple here, but I'm at a loss. Any help would be greatly appreciated. For reference, additional info from the BLS on their API can be found at this link:
https://www.bls.gov/developers/api_signature_v2.htm
Try using this,
const data = { username: 'example' };
fetch('https://api.bls.gov/publicAPI/v2/timeseries/data', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
But what I think the real problem might be that you are using an API which has authentication used, so make sure that you are using the api key along with the post req itself.
if you can have the api documentation, please refer it and see how to make a authenticated request to the server.
If you want to use regular JavaScript's fetch in Node.js, it won’t work, One reason for that is because, NodeJs doesn't make requests via the browser, but Fetch API was made to make requests via the browser
You’d have to use a package called node-fetch, it's just like the regular fetch, but for NodeJs.
You can get it here -> https://www.npmjs.com/package/node-fetch
or you can also use the standard NodeJS HTTP package.
or packages like axios or request to make HTTP requests in NodeJS

getting problem performing a post request to an external API

I'm using axios to perform get and post requests to an external api,
i have finally succeed to achieve get request (problem with the ssl certificate, i avoid it by adding this :
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
now i would like to post the api,
to get the request working in postman, i put in
headers content-type : application/json
and in the body : {}
like here
when trying with a google chrome extention, to make it work, i put nothing in the headers but in params, i select customer : application/json and i put inside this {} instead of the default choice which is x-www-form-urlencoded;charset=UTF-8
chrome extention
in my javascript app i tried this
var url = https://10.11.31.100:9440/api/nutanix/v3/images/list;
axios({
method:'post',
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
url,
auth: {
username: '******',
password: '********'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
params: {},
data: {}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I get this problem :
TypeError : UTF-8 is not a function
Specifically with regards to the Nutanix v3 REST API - this is probably because the POST request above doesn't have an appropriate JSON payload i.e. the "data" parameter is empty.
When sending Nutanix v3 API POST requests, specifically to "list" entities, you'll need to specify the "kind" of entity being listed. In your example, the JSON payload below will work.
{"kind":"image"}
See here: https://nutanix.dev/reference/prism_central/v3/api/images/postimageslist
HTH. :)

Resources