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
Related
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!
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
}
});
var request = require('request');
var options = {
'method': 'POST',
'url': 'http://',
'headers': {
},
form: {
'username': '',
'password': ''
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
transforming this to axios request:
let data = qs.stringify({ 'username': '',
'password': '' })
const options = {
method: 'POST',data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded'},
url: '',
};
response[0] = await Axios(options).then((res) => {
console.log("res",res)
return res.data
}
).catch((err) => {
console.log("err status", err.response.status)
return err.response.data
});
gives an error and the headers shown doesnt have the url encoded:
url: '',
method: 'post',
data: 'username=&password=',
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.19.2'
},
Why the content-type : url-encoded is not in the headers and only the Accept: 'application/json, text/plain, /' is showing.
You are not showing which error you are receiving but the way you are setting the Axios call seems right following the Axios documentation. So I suspect it is a problem on how you have set up your Node.js server.
If you are using Express.js v.4+, probably you forgot to set up in your server the directive to parse application/x-www-form-urlencoded content type as explained here in the official documentation.
app.use(express.urlencoded({ extended: true }))
If you are using the body-parser package you need to set up your server with:
app.use(bodyParser.urlencoded({extended: true}));
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()
How to get the PayPal access-token needed to leverage the REST Api by using node?
Once you have a PayPal client Id and a Client Secret you can use the following:
var request = require('request');
request.post({
uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"content-type": "application/x-www-form-urlencoded"
},
auth: {
'user': '---your cliend ID---',
'pass': '---your client secret---',
// 'sendImmediately': false
},
form: {
"grant_type": "client_credentials"
}
}, function(error, response, body) {
console.log(body);
});
The response, if successful, will be something as the following:
{
"scope":"https://api.paypal.com/v1/payments/.* ---and more URL callable with the access-token---",
"access_token":"---your access-token---",
"token_type":"Bearer",
"app_id":"APP-1234567890",
"expires_in":28800
}
Also, you can use axios, and async/await:
const axios = require('axios');
(async () => {
try {
const { data: { access_token } } = await axios({
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'post',
headers: {
Accept: 'application/json',
'Accept-Language': 'en_US',
'content-type': 'application/x-www-form-urlencoded',
},
auth: {
username: client_id,
password: client_secret,
},
params: {
grant_type: 'client_credentials',
},
});
console.log('access_token: ', access_token);
} catch (e) {
console.error(e);
}
})();
Modern problems require modern solutions:
const fetch = require('node-fetch');
const authUrl = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
const clientIdAndSecret = "CLIENT_ID:SECRET_CODE";
const base64 = Buffer.from(clientIdAndSecret).toString('base64')
fetch(authUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Authorization': `Basic ${base64}`,
},
body: 'grant_type=client_credentials'
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data.access_token);
}).catch(function() {
console.log("couldn't get auth token");
});
You could use PayPal-Node-SDK to make calls to PayPal Rest APIs. It handles all the authorization and authentication for you.
Here is how I get the access_token using superagent
superagent.post('https://api.sandbox.paypal.com/v1/oauth2/token')
.set("Accept","application/json")
.set("Accept-Language","en_US")
.set("content-type","application/x-www-form-urlencoded")
.auth("Your Client Id","Your Secret")
.send({"grant_type": "client_credentials"})
.then((res) => console.log("response",res.body))