Error handling axios request.post - node.js

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.

Related

Make Request With Node.JS To Change Vanity Discord

How can I change the vanity url code in Discord? My current code returns a 401 error.
Code:
const fetch = require("node-fetch");
setTimeout(async () => {
await fetch('https://www.discord.com/api/v9/guilds/serverID/vanity-url', {
method: 'POST',
headers: { 'Authorization': 'Bot ' + client.token, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"terbo1"
})
})
.then(async res => await res.json())
.then(json => { console.log(json);});
Response:
{ message: '401: Unauthorized', code: 0 }
I don't understand why you need setTimeout however you were using the wrong HTTP method on the request: the correct method is PATCH.
Additionally, payload isn't an option on the Fetch API, use body instead.
const fetch = require("node-fetch");
const endpoint = `https://www.discord.com/api/v10/guilds/${SERVER_ID}/vanity-url`;
await fetch(endpoint,{
method: "PATCH",
headers: {
Authorization: `Bot ${client.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "terbo1",
}),
});
Edit: As of 01/12/2022 (12/01/22) Discord have now disabled this ability for bots to "manipulate" this request, however, the above script can be used on a User-Account, there are risks of being banned doing so, so it is NOT recommended, use at your own risk.

How to make httpRequest from parser cloud server(back4app) to another server

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

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

SurveyMonkey API Create a Survey using NodeJS

I created a small server using NodeJS/Express and I'm using node-fetch to interact with SurveyMonkeys API. I currently have two surveys on my account which I can view through their Postman collection. But when I try to use my own endpoints, it doesn't seem to work. The GET request to view all of the surveys returns a status code of "200" but responds with:
{
"size": 0,
"timeout": 0
}
The POST request to create a survey gives me a status code of "400" but returns the same response. Here is my code so far.
const router = require("express").Router();
const fetch = require("node-fetch");
const TOKEN = process.env.SM_ACCESS_TOKEN;
const BASEURL = process.env.SM_BASEURL;
const options = method => ({
headers: {
Authorization: `Bearer ${TOKEN}`,
"Content-Type": "application/json",
method: method
}
});
/*
GET a list of surveys
*/
router.get("/", async (req, res) => {
try {
const surveys = await fetch(`${BASEURL}surveys`, options("GET"));
console.log(surveys);
if (surveys) {
return res.status(200).json(surveys);
}
} catch (err) {
console.log(err);
res.status(500).send({ message: "Server error", err });
}
});
router.post("/create-survey", (req, res) => {
const surveyData = req.body;
fetch(`${BASEURL}surveys`, {
method: "POST",
body: surveyData,
headers: {
Authorization: `bearer ${TOKEN}`,
"Content-Type": "application/json"
}
})
.then(data => {
return res.status(data.status).json(data);
})
.catch(err => console.log(err));
});
module.exports = router;
Additional information:
I am able to complete all of these actions using the POSTMAN collection provided by SurveyMonkey with my Access Token. BASEURL = "https://api.surveymonkey.com/v3/".
ServeyData = { "title": "Some Title" }
Resolved this issue by switching out of node-fetch and instead using axios. Could be the fetch vs xhr request I think.

ExpressJS: Send Request Header Authentication

I have an API to authenticate the user with LDAP and I have been provided with the information which includes Content-Type: application/json and username and password for the request header and then the user's username and password to be passed in body. I tried the below code but it's not working. I want to know if I am passing the header request correctly or not.
router.post('/user', function(req, res){
var auth = {
content-type: "application/json",
username: "abcd",
password: "xyze"
}
auth.post('/user', {username: req.body.username, password: req.body.password"}, function(response) {
console.log(response);
})
})
Consider use axios package to make your requests: https://www.npmjs.com/package/axios
This link has a section “Creating an instance showing how you can set the header:
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
Once the header is set, invoke the post method, like this:
instance.post('/my/specific/endpoint/', myData);
In the following example, you can pass an authentication token as the header to your request:
import axios from 'axios';
const MY_BASE_URL = 'https://www.myserver.com/';
class MyLdapService {
static xhr(accessToken) {
const options = {
baseURL: MY_BASE_URL,
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
};
return axios.create(options);
}
static async myPostEndpoint(accessToken, data) {
return new Promise((resolve, reject) => {
this.xhr(accessToken).post('my-endpoint/', data)
.then(result => resolve(result.data.card))
.catch(err => reject(this.createError(err)));
});
}
}
So you can invoke the POST endpoint like this:
MyLdapService.myPostEndpoint('my_access_token', {});

Resources