I have a JSON object that I wish to send to a server using the server's API key. I wish to have a retry count of 3 so that I can retry sending data if previous calls fail.
I am not sure whether to use 'axios-retry' or 'retry-axios'.
How do I configure the Content-Type in the header, and where do I add the API key and the data to be sent. My present code looks like this:
const axiosRetry = require('axios-retry');
axiosRetry(axios, { retries: 3 });
var data = { /*----My JSON Object----*/ };
axios.post('my url', data, {
headers: {
'Authorization': 'API_Key',
'Content-Type': 'application/json'
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
Use axios instead, it is a Promise based HTTP client for the browser and node.js
var axios = require('axios')
axios.post(url,data, {
headers: {
'authorization': your_token,
'Accept' : 'application/json',
'Content-Type': 'application/json'
}
}).then(response => {
// return response;
}).catch((error) => {
//return error;
});
Related
How to make http request from parse cloud server(back4app) to another server, here i am making request to fake json api https://jsonplaceholder.typicode.com/todos/1
main.js
Parse.Cloud.define("hello", async (request) => {
return Parse.Cloud.httpRequest({
url: 'https://jsonplaceholder.typicode.com/todos/1',
followRedirects: true,
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(function(response){
console.log(response.text)
//return response.text;
//return response.success(response.text)
//resData=100;
return 100; //i am not even returning the response,i am returning a just a const
},function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
})
});
App.js
const cloudFunction=async()=>{
const someVar=10
Parse.Cloud.run('hello').then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(JSON.stringify(error))
})
}
can some body help,thank you good people of stackoverflow
I want to upload image to the database. However, when I use fetch method with 'Content-Type': 'multipart/form-data' but I cannot get the appended data in the server side. It shows that I have no data in the body.
Below is fetching part of the coding
editProfile = () => {
let bodyData = new FormData();
let photo={
uri:this.state.uri,
type:this.state.type,
fileName:this.state.fileName,
}
bodyData.append('transactionCode', 'UPDATEPROFILE');
// bodyData.append('photo', photo);
console.log(bodyData);
fetch(URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: bodyData,
}).then((response) => response.json())
.then((responseJson) => {
alert(responseJson);
})
.catch((error) => {
alert(error);
});
}
This is the example of how i check the data at the server side
const custfunction = function (req, res) {
console.log(req.body);
}
When i console.log(req), it shows body:{} is empty
Alright, I just find out the problem. I need to use Multer to handle multipart/form-data in the backend. Thanks a lot.
https://www.npmjs.com/package/multer
Is there a way to send a post request in nodeJS and specify th content-length.
I tried (using axios):
let data = `Some text data...........`;
let form = await Axios.post(
"url.......",
data,
{
headers: {
Authentication: "token.....",
"Content-Type": "multipart/form-data; boundary=c9236fb18bed42c49590f58f8cc327e3",
//set content-length manually
"Content-Length": "268"
}
}
).catch(e => e);
It doesn't work, the length is set automatically to a value other then the one I pass.
I am using axios but open to using any other way to post from nodeJS.
I can't add a comment because of low reputation, but part of Sandeep Patel's answer regarding Axios is outdated. You can set Content-Length manually. Axios will not override Content-Length if content-length header is present:
// Add Content-Length header if data exists
if (!headerNames['content-length']) {
headers['Content-Length'] = data.length;
}
Source: https://github.com/axios/axios/blob/main/lib/adapters/http.js#L209-L213
So in your case it would be:
let data = `Some text data...`;
let form = await Axios.post(
"url...",
data,
{
headers: {
Authentication: "token....",
"Content-Type": "contentType...",
//set content-length manually
"Content-Length": "268",
"content-length": "268"
}
}
).catch(e => e);
In Axios, If data is present it will set length calculated from data, so even if you pass header content-length, it will be overridden by code:
Check this out for more details:
https://github.com/axios/axios/blob/master/lib/adapters/http.js
Using http or https module you can do:
const https = require('https')
const data = JSON.stringify({
key:values
})
const options = {
hostname: 'example.com',
port: 443,
path: '/testpath',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
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 am trying to post large json to a http server(a grafana server actually):
here is my code:
const http = require('http')
const request = require('request')
const fs = require('fs')
const opts = {
hostname: 'myip',
port: 3000,
path: '/api/dashboards/uid/KPEiIQVWk',
method: 'GET',
timeout: 5000,
headers : {
'Authorization' : 'Bearer ********************************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
}
const req = http.request(opts, res => {
console.log(`Fetch: statusCode: ${res.statusCode}`)
var origin = ''
res.on('data', d => {
origin += d
})
res.on('end', function(){
dash = JSON.parse(origin)
dash.dashboard.panels.forEach(p => {
if(p.id == 26){
fs.readFile(__dirname + '/grafana/pm/branch-graph.html','utf-8', function(err, newPanel){
if(err){
console.log(err)
}
p.content = newPanel
const fresh = JSON.stringify(dash)
const updateOptions = {
uri: 'http://myip:3000/api/dashboards/db',
method: 'post',
headers : {
'Authorization' : 'Bearer *************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Content-length' : fresh.length
},
json: fresh
}
fs.writeFile('tmp.json', fresh, function(err){
if(err){
console.error(err)
}
})
request(updateOptions, function(error, response, body){
console.log(`update: statusCode=${response.statusCode}`)
console.log(`update: ${body}`)
})
})
}
})
})
})
req.on('error', error => {
console.error(error)
})
req.on('timeout', () => {
req.abort()
})
req.end()
as you can see, I first fetch a grafana dashboard's source, then make some udpate, then post it back to grafana server. but always get 400 error. The strange thing is that if I dump the json to a file and use curl to post, it will work.
curl -vH "Authorization: Bearer $TOKEN" -H "Expect:" -d #tmp.json -H "Content-Type:application/json" http://myip:3000/api/dashboards/db
the whole json is about 40000+ bytes. any hint on this? I am not very famillar with nodejs. I am just trying to write some CI scripts.
First, I don't think it's necessary to use both the http and request modules. http is a module built into nodejs, and request is an npm package.
I recommend you use the npm request package because it's easier. You can read its documentation here: https://www.npmjs.com/package/request#http-authentication
Second, the options you're passing to the request module is not formatted correctly, I think this is why it is not working. With your current code, I would console.log('POST error', error); to print out the error. The correct options for the request module is proposed below.
const options = {
url: 'https://myip:3000/api/dashboards/db',
body: fresh, // the json from the fs.read callback
auth: {
'bearer': 'bearerToken'
},
json: true // from docs: If json is true, then body must be a JSON-serializable object.
}
request.post(
options,
(err, httpResponse, body) => {
console.log(err, body);
});
I am trying to post a track uri and playlist Id to spotify API in order to add a track to a playlist.
I am using the url params and only one track at a time because spotify say you can do this 'The Spotify URIs of the tracks to add can be passed either in the query string or as a JSON array in the request body.' - spotify
The request hangs, nothing happens. No error, no response. In postman If I use the same bearer auth and url, I get the 'snapshot_id' as response, this is what I am looking for with the code.
I have tried an axios post and a fetch post, both behave the same.
async function updatePlaylist(accessToken, reqParams) {
console.log('PARAMS _', reqParams);
console.log('token _', accessToken);
console.log('trying...');
const url = `https://api.spotify.com/v1/playlists/${reqParams.playlist_id}/tracks?uris=${reqParams.track_uri}`;
return fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + accessToken
},
contentType: 'application/json'
}).then((response) => {
console.log('response promise is ', response.json())
return response;
}).catch(err => {
console.error(err);
throw new Error('Update playlist call failed');
});
}
async function updatePlaylist(accessToken, reqParams) {
console.log('PARAMS _', reqParams);
console.log('token _', accessToken);
console.log('trying...');
const url =
`https://api.spotify.com/v1/playlists/${reqParams.playlist_id}/tracks?uris=${reqParams.track_uri}`;
return axios.post(url, {
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
}
}).then((response) => {
console.log('response promise is ', response)
}).catch(err => {
console.log('errrring ',err)
if (err.response.status === 401) {
return {statusCode: 401};
}
console.error(err);
throw new Error('Get all play lists call failed');
});
}
All my variables are there. I expect the 'snapshot_id' returned back to me confirming the update.
Any help most welcome.
Have you tried setting your content-length to 0 in the headers?
For example in the axios implementation it'd be like this
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json',
'Content-Length': '0'
}
Source