Send Post request with Headers in Nestjs - node.js

I am trying to use Nestjs to send a Post request to a 3rd party API which requires authorization (client-key and secret). Would anyone know how to attach headers in a request. I want to use axio's HttpService.

give the HttpService post request a custom headers object
this.httpService.post('http://www.stackoverflow.com', { my: 'data' }, { headers: { 'x-custom-header': "this a header" }})
would result in a POST request with { my: 'data' } as payload and a custom header x-custom-header: this is header
underlying the nest HttpService there is an axios instance so you will find more information in the axios doc

Related

Modiy axios request 'data' field into 'body'

I'm trying to create a POST request using axios to a Notification API. So this Notification API have been developed before thus I cannot change anything related to it.
It accepts the request more or less like below.
I need to have the request body in the field called body as shown below. However, axios sends the request body in the field called data rather than body
Expected request
{
"head": {
...
},
"body":{
"publicUserId":"abcd",
"merchantId":"123888",
}
},
}
My request composed automatically by axios:
Axios request
{
"head": {
...
},
"data":{
"publicUserId":"abcd",
"merchantId":"123888",
}
},
}
I did try searching for how to alter the request body field name to body instead of data but I'm pretty sure I haven't found the solution. Maybe if anyone here has some workarounds, I'd be glad to try.
Should any details need to be provided, please tell me. Thank you.

Node.js Axios HTTP request with bearer token returning undefined

I've seen many posts on Stack that are close to what I need, but don't fully answer my question (I'm pretty green with Node). I'm working on connecting a Twitch/Tiltify donation campaign to a Raspberry Pi via Node.js/Axios. I'd like the Pi to regularly check for new donations, then activate physical circuits (solenoid valves etc.) to be viewed live on the stream. Here's my code so far:
const axios = require('axios');
axios.get('URL_GOES_HERE', {
headers: {
'Authorization' : 'Bearer MY_TILTIFY_ACCESS_TOKEN'
}
})
.then(response => {
console.log(response.data.url);
console.log(response.data.explanation);
})
.catch(error => {
console.log(error);
});
I assume that MY_TILTIFY_ACCESS_TOKEN is the access token I generated from within my Tiltify account. I'm confused, however, about what value to put in URL_GOES_HERE. The somewhat sparse Tiltify API docs give two possible URLS: https://tiltify.com/oauth/authorize and https://tiltify.com/oauth/token. Or am I supposed to put my bearer credentials directly into the URL of a useful request, like https://tiltify.com/api/v3/user? I've tried all three, and I just get undefined undefined in the console.
A nudge in the right direction is appreciated! Thanks for your time.
#benstepp over on Github ultimately answered my question. Here's the code he provided:
const axios = require('axios');
axios.get('https://tiltify.com/api/v3/campaigns/MY_CAMPAIGN_ID/rewards', {
headers: {
'Authorization' : 'Bearer MY_API_TOKEN'
}
})
.then(response => { // this is an axios response object (https://github.com/axios/axios#response-schema)
//console.log(response.data); // this is the response body from tiltify (https://tiltify.github.io/api/endpoints/campaigns-id-donations.html)
//console.log(response.data.data); // this is the .data property of our responses
response.data.data.map((reward) => {
// the name/amount of the recent donations
console.log(`${reward.name}`)
})
})
.catch(error => {
console.log(error);
});
The /authorize endpoint is used for the Web Server OAuth Authentication Flow and User-Agent OAuth Authentication Flow.
The /token endpoint is used for the Username-Password OAuth Authentication Flow and the OAuth Refresh Token Process.
So first you need to get Authorized to be able to use Tiltify api. For that you need to use either of the flow
https://tiltify.com/oauth/authorize
https://tiltify.com/oauth/token
Assuming you used token route, you will get a response something like this:
{ "access_token":"token", "token_type":"bearer", "refresh_token":"refresh_token" }
Then using the access_token you got from the response you will call the api routes so in URL GOES HERE will be your api routes like
/campaigns/:id
causes/:id
with which you'll use Authorization: Bearer <access_token> in headers

getting 403 error while sending file to githib via REST using nodejs

I want to send multiple files to Github repository via nodejs. Tried several approaches and end up using node-rest-client module. Tried below code send a sample file to repository called 'metadata'. But after post I am getting error message "Request forbidden by administrative rules. Please make sure your request has a User-Agent header"...please let me know if anyone faced this error before and get rid of it.
convertval = "somedata";
var dataObj = {
"message": "my commit message",
"committer": {
"name": "Scott Chacon",
"email": "ravindra.devagiri#gmail.com"
},
"content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}
debugger;
var Client = require('node-rest-client').Client;
var client = new Client()
var args = {
data: dataObj,
headers: { 'Content-Type': 'application/json' },
};
client.post("https://api.github.com/repos/metadata/contents", args, function (data, response) {
console.log("file send: True : " + data);
});
According to the REST API:
All API requests MUST include a valid User-Agent header. Requests with
no User-Agent header will be rejected.
First of all, you need to define 'User-Agent' with value 'request' in your request header. Refer to this link.
Second, endpoint you are trying to call might require authentication. Generate a personal token from here, add that token in your request header, 'Authorization': 'token '.
If you're using Git extensively in your code, I suggest you to use this - Nodegit.
Edit:
I don't think sending multiple files in a single request is possible in 'Contents' endpoints group (link).
You can checkout Git Data API (as discussed here).

Node - post xml to server with request

I try to communicate with a REST api via xmls. I generate an xml and test it with Restlet Client (a chrome extenson for testing REST APIs).
It works fine, I receive the response XML.
If I try to send with request-promise, I receive
'<html><head><title>Error</title></head><body>Internal Server Error</body></html>'
in err.response.body.
The response from the API server is always XML, so I do not get why it is 'html'.
Here is the code
options = {
uri: uri,
header: {
'Content-Type': 'application/xml ',
'Accept' : 'application/xml '
},
body: xml // I use the same xml in Restlet Client's body
}
rp.post(options).then(response=>{
console.log('------SUCCESS-----')
console.log(response)
}).catch(err=>{
console.log('------ERROR-----')
console.log(err.response)
})
If you need any plus information, please let me know.

Intercept sending request to change a header with request library

I am using the infamous request library to send requests.
One of those requests requires me to send the header multipart/mixed; boundary={myboundary}.
Request is using the form-data library for such requests but it does not set the Content-Type header properly. Therefore I would need to set it like this:
let req = request.post({url: "https://..."}, formData: formData)
req.setHeader('Content-Type', `multipart/mixed; boundary=${req.form().getBoundary()}`)
Sadly I can't add/alter any headers after firing the request. Therefore I want to know whether there is a way to intercept the sending so I can change the header?
You will need to use the multipart option instead of formData to use other, arbitrary multipart/* content types. Each object in the multipart array contains the headers to send in that part. The one exception is the body property which is used as the actual body of that part.
request.post({
url: 'https://...',
multipart: [
{ 'X-Foo-Header': 'bar', body: 'baz' },
// ...
],
headers: { 'Content-Type': 'multipart/mixed' }
});
The boundary should be automatically appended for an existing, explicit Content-Type header. This request test explicitly tests for this behavior.

Resources