How to make httpRequest from parser cloud server(back4app) to another server - node.js

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

Related

Axios bad request status 400

I'm having this issue AxiosError: Request failed with status code 400
I checked the console and I test manually the url and It worked, so I don't know what's wrong, this code:
//file controller.js
//Set Create Session
exports.setSession = async (req, res) => {
const data = await request({
path: process.env.APP_LOCALHOST_URL + urlLogin.setCreateSession,
method: 'POST',
body: JSON.stringify(req.body)
});
return res.json(data);
}
//file request.js
exports.request = async ({path, method = "GET", body }) => {
try {
const response = await axios({
method: method,
url: path,
headers: {
'Content-Type': 'application/json'
},
body: body
});
return response;
} catch (error) {
console.log("error: ", error);
}
}
the function setSession is to call in my routes file, and the function request is my reusable component. My intention is to use the function request in many functions, these could be of the GET, DELETE, PUT, POST, PATCH type.
So, currently I get this on console:
data: {
error: '5',
errorId: 'badRequest',
errorString: 'Internal error: Undefined JSON value.'
}

'Axios' show Error: Network Error on server returning with 200 http status

I am using axios: "^0.19.0" to create get and post requests in react-native 0.60.4, but even after backend returning HTTP status code 200 axois showing Error: Network Error. Working perfectly on iOS but not on Android.
My request:
export default function uploadImageWithData(formData, url = "createGroup") {
return new Promise((resolve, reject) => {
axios({
method: "post",
url: BASEURL + "api/webservice/" + url,
data: formData,
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${global.authToken}`
}
})
.then(response => {
resolve(response);
})
.catch(err => {
console.log("error: ", err);
reject(err);
});
});
}
Kindly help.
The issue with formData, in formData empty array appending in formData causing the issue(For Android).

Proxy API request through Express return pending Promise instead of response

I am currently trying to work with the Atlassian Jira rest API. In order to not get a CORS error I go through the recommended route of not sending the request from the browser but proxy it through my express server.
Now as I am doing this, all I receive back in the app is a pending promise. I assume that I have not correctly resolved it at one point but I cant figure out where.
API Handler sending the request to the proxy:
const baseURL = `${apiConfig}/jiraproxy`;
export const testConnection = integration => {
return fetch(`${baseURL}/get`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(integration)
})
.then(handleResponse)
.catch(handleError);
};
Jira Proxy Endpoint on the Express Server
const baseURL = `rest/api/3/dashboard`;
router.post("/get", (req, res) => {
fetch(req.body.link + baseURL, {
method: "GET",
headers: { Accept: "application/json" },
auth: {
username: req.body.credentials.username,
password: req.body.credentials.token
}
})
.then(handleResponse)
.catch(handleError);
});
handleResponse & handle Error Methods:
async function handleResponse(response) {
if (response.ok) {
return response.json();
}
if (response.status === 400) {
const error = await response.text();
throw new Error(error);
}
throw new Error("Network response was not ok.");
}
function handleError(error) {
// eslint-disable-next-line no-console
console.error(`API call failed. ${error}`);
throw error;
}
Goal:
Send the request of sending a request to the proxy and return the resonse of the proxy as the return of the initial "testConction" method.
Error:
No errors thrown, but the response received in the Browser is a pending promise.
Change to the Jira Proxy router fixed it. Thanks to #jfriend00.
router.post("/get", (req, res) => {
return fetch(req.body.link + baseURL, {
method: "GET",
headers: { Accept: "application/json" },
auth: {
username: req.body.credentials.username,
password: req.body.credentials.token
}
})
// This is the part that changed
.then(response => handleResponse(response))
.then(jiraResponse => res.status(200).json(jiraResponse))
.catch(handleError);
});

HTTP call to send data to server using Axios/Axios-retry

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;
});

Error handling axios request.post

We have an axios method like
export function callAcme(message) {
const requestUrl = `/api/acme/message`;
return {
type: ACME_MESSAGE,
promise: request.post(requestUrl, {
data: message
})
};
}
This method is mapped to an express router method, which makes a call to a third party API to get some data.
router.post("/acme/message", (req, res) => {
const { data } = req.body;
const url = "third/party/url/action;
authenticateThirdparty({
user: req.user
}).then(userToken => request({
method: "post",
url,
data: body,
baseURL: url,
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-cache",
headers: {
Authorization: `Bearer ${userToken}`
}
})).then((response) => {
res.status(200).send(response.data);
}).catch((error) => {
res.status(error.status).send(error.data);
});
});
The third party call is made in a try catch block. But id the third party method raises some error then we are are unable to send the error back to the web page who initiated the the axios call.
ie. In the client which invokes callAcme will not get the error object back.

Resources