Having made a successful request to https://api.heroku.com/sources, I'm now attempting to upload a file to the put_url returned.
In postman this is working a treat. However, when I attempt to do the same in Axios no good. I've attached a screenshot of the postman with the 200 status.
So far I've the following....
const data = fs.readFileSync(zipPath, 'utf-8');
var config = {
method: 'put',
url: put_url,
headers: {
'Accept-Encoding': 'gzip, deflate, br',
'Content-Type': 'text/plain; charset=utf-8',
'Content-Length': Buffer.byteLength(data),
},
data,
};
await axios(config);
Which results in the following error SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method
I've played around with the encoding, and content types (pretty much stabbing in the dark tbh)
Annoyingly, I've got it working with this:
const post_data = fs.readFileSync(path.join(__dirname, 'compare-api.tar.gz'));
const options = {
method: 'PUT',
hostname: host,
path: put_url.substring(httpHost.length),
headers: {
Host: host,
'Accept-Encoding': 'gzip, deflate, br',
'Content-Length': Buffer.byteLength(post_data),
},
};
const req = https.request(options, function (res) {
res.on('data', function () {
// Can't remove this even though it's doing nothing :(
});
res.on('end', function () {
cb(null, source_blob);
});
res.on('error', function (error) {
console.log('error', error);
cb(error);
});
});
req.write(post_data, 'utf-8');
req.end();
But I'd much rather it worked in Axios.
After what seemed like forever....
'Content-Type': ''
...did the trick!
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 am trying to create script that could post comment in my thread on steam with node and request lib. Trying to achieve by doing something like this:
const body = {
comment: 'Sometext',
count: '15',
sessionid: session_id,
}
bumpingDiscussionsPostsModule.bumpInDiscussion=async() => {
const postHeader = {
method: 'POST',
uri: urlPost,
headers: {
Cookie: cookie
},
form: JSON.stringify(body)
}
const response = await request(postHeader);
console.log(response);
}
Tho steam keeps returning me returning {"success":false}, any clues what I am doing wrong?
I was just formatting it wrong. If someone might be looking for it, this gets the job done:
const doBump = await fetch(bumpingUri, {
method: 'post',
body: `comment=${process.env.BUMP_COMMENT}&count=15&sessionid=${process.env.CONN_SESID}&extended_data=${process.env.EXTENDED_DATA}&feature2=${featureID}oldestfirst=true&include_raw=true`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'accept': 'text/javascript, text/html, application/xml, text/xml, */*',
Cookie: process.env.CONN_STRING
}
});
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'm having issues with authentication when I change from httpreq to axios' post. I need to use multipart/form-data. For some reason it isn't working in axios, but it is in httpreq. What am I missing?
httpreq:
postType1ToServer: function(request, callback) {
var options = {
headers: {
'Content-Type': 'multipart/form-data',
Connection: 'keep-alive',
Authorization: request.type1msg
},
agent: keepaliveAgent
};
return httpreq[request.method](request.options.url, options);
versus axios
postType1ToServer: function(request, callback) {
var options = {
headers: {
'Content-Type': 'multipart/form-data',
Connection: 'keep-alive',
Authorization: request.type1msg
},
httpAgent: new http.Agent({ keepAlive: true })
};
return axios
.post(request.options.url, options)
.then(function(response) {
console.log(response);
})
.catch(function(response) {
console.log(response);
});
See the documentation:
axios.post(url[, data[, config]])
You've put the config where the data is supposed to be, and missed the data out entirely.
You can try to remove backslash form URL at end of it
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.