express post api isnt executing when sent string is 18 characters long - node.js

When i get the string from my discord bot, i make a post request to my api
axios.post(`http://localhost:8080/api/post/ban/${discord_id}`, {}, {
headers: {
key: key
}
}).then((response) => {
console.log(response.data)
})
But when its submitted the event isnt activated
When i sent string the length of 17 or less or length of 19 or more it worked but not when string length is 18
app.post('/api/post/ban/:discord_id/', async function (req, res) {
let id = req.params.discord_id
let header = req.headers;
if(isNaN(id)) return res.send({
"error": {
"message": "USER_ID_MUST_BE_NUMBER",
"code": "400"
}
});
if(id.length < 19 || id.length > 19) return res.send({
"error": {
"message": "ID_IS_NOT_VALID",
"code": "400"
}
});
if(header.key != key) return res.send({
"error": {
"message": "OWNER_ONLY",
"code": "none"
}
});
await banModel.findByIdAndUpdate(banID, {
$addToSet: { "bannedUsers": `${id}`}
});
return res.send({
"success": {
"message": "ADDED_USER_TO_BANS",
"code": "201"
}
});
});`

i fixed it heres the answer:
axios.post(`http://localhost:8080/api/post/ban/${discord_id}/`,{},{
headers: {
key: key
}
})
.then(function (response) {
console.log(response.data)
if(response.data.error) {
switch(response.data.error.code) {
case "404":
return interaction.reply("Channel not found!");
case "422":
return interaction.reply("Invalid parameters!");
case "400":
return interaction.reply("Invalid types of objects!");
case "409":
return interaction.reply("U already exist on our Database!");
case "none":
switch(response.data.error.message) {
case "INVALID_VIDEO_URL":
return interaction.reply("Invalid video url")
case "OWNER_ONLY":
return interaction.reply("Owner only API")
}
break;
}
}
if(response.data.success) return interaction.reply("Succesfully added your video!")
})
.catch(function (error) {
console.log(error);
});

Related

API response from inomnia is different than the error (from yup validator) on client side

So I am using yup validator
beeraverage: yup.number("Not a number").min(0).nullable(true),
testing with "beeraverage": "4.5.9", in the object. Then I get this with insomnia:
As expected.
Using this code to catch up the yup error:
.catch(yupError => {
const errors = yupError.inner.reduce((acc, error) => {
const { path, message } = error;
if (!acc.hasOwnProperty(path)) {
acc[path] = [message];
}
else {
acc[path].push(message);
}
return acc;
}, {});
res.status(errorCode).json(new InvalidFieldErrorResponse(
'Data invalid',
errors,
errorCode
));
});
(Btw how can I get the error "Not a number" written in the code above in the validator ???)
and then when I try in the client side using axios :
axios.put('http://10.0.2.2:8080/api/bar/' + id, changes, { headers: { "Authorization": `Bearer ${token}` } })
.then(function (response) {
console.log("reponse update bar: " + JSON.stringify(response.data.result, null, 4));
setResponse(response.data.result);
})
.catch(function (error) {
console.log("error update bar: " + JSON.stringify(error, null, 4));
setError(error.message);
})
.finally(function () {
setLoading(false);
});
I get an error completely different and nothing to do with it :
How can I get the errors from yup in the client side please ?
So because axios encapsulate it, the error call that you get in insomnia/postman is:
error.response.data
and map on error.response.data.fieldErrors
And for the custom error message:
beeraverage: yup.number().typeError("Not a number").min(0).nullable(true),
and to get the fields errors:
axios.put('http://10.0.2.2:8080/api/bar/' + id, changes, { headers: { "Authorization": `Bearer ${token}` } })
.then(function (response) {
//console.log("reponse update : " + JSON.stringify(response.data.result, null, 4));
setResponse(response.data.result);
})
.catch(function (error) {
var errors = "";
for (const fields in error.response.data.fieldErrors) {
console.log("fields: " + JSON.stringify(fields, null, 4))
error.response.data.fieldErrors[fields].map(item => (
errors = errors.concat("\n" + item)
))
}
setError(errors);
})
.finally(function () {
setLoading(false);
});

Bad request - header is required - Hapijs

I am using hapijs to create a simple route. The joi validation to check for header is throwing me an error although the header is passed
server.route({
method: 'GET',
path: '/myresponse',
handler: async (request: Request, reply) => {
try {
return reply.response('ddd');
} catch (error) {
const response = reply.response(error.data).code(error.statusCode);
return response;
}
},
options: {
validate: {
failAction: (request, h, err) => {
console.log(request.headers)
throw err;
},
headers: joi.object({
'cusHeader': joi.string().required()
}),
options: {
allowUnknown: true,
abortEarly: false
}
}
}
});
}
I want the user to pass the header cusHeader and its value should be of type string. I am passing the header in the postman request but it still throws me the below error,
{
"statusCode": 400,
"error": "Bad Request",
"message": "\"modalPath\" is required",
"validation": {
"source": "headers",
"keys": [
"cusHeader"
]
}
}
I don't know where I am wrong.

How to receive re-requested data when data requested by mounted() is re-requested by aixos interceptor

the code below is the first request for get list data
mounted() {
this.getList()
},
methods: {
handleClick(row) {
console.log(row.id)
console.log(row.url)
this.$router.push({ name: 'Main', query: { id: row.id } })
},
getList() {
axios
.get('/api/v1/requests/all', {
params: {
userId: this.$store.state.userInfo.id,
},
})
.then(response => {
let moment = require('moment')
for (var item of response.data.data) {
item.createdAt = moment(item.createdAt).format(
'YYYY-MM-DD HH:mm:ss',
)
}
this.items = response.data.data
})
.catch(error => {
console.log(error)
})
}
my interceptor
axios.interceptors.response.use(
function (response) {
return response
},
async function (error) {
const originalRequest = error.config
if (error.response.status === 401 && !originalRequest._retry) {
error.response.config._retry = true
sessionStorage.removeItem('access-token')
let headers = {
grant_type: 'refresh_token',
Authorization: sessionStorage.getItem('refresh-token'),
}
axios
.post('/api/v1/users/refresh_token', {}, { headers: headers })
.then(response => {
let token = response.data.data
sessionStorage.setItem('access-token', token)
originalRequest.headers['Authorization'] = token
originalRequest.headers['grant_type'] = 'grant_type'
return axios.request(originalRequest)
})
.catch(error => {
console.log(error)
alert('blablabla.')
})
}
return Promise.reject(error)
},
)
the flow is i understand
1.token expired
2.move to list page
3.mounted hook is request data
4.getList -> axios get('~~request/all')
5.interceptor->axios post('~~~refresh_token')
6.re request with new token(request/all)
7.re request is 200, but not update list page
i'd really appreciate your help :)
Seems like you need to return the second request (await for result and return). Right now the result of second request seems to be ignored
axios.interceptors.response.use(
function (response) {
return response;
},
async function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
error.response.config._retry = true;
sessionStorage.removeItem("access-token");
let headers = {
grant_type: "refresh_token",
Authorization: sessionStorage.getItem("refresh-token"),
};
const [secondError, res] = await axios // await here
.post("/api/v1/users/refresh_token", {}, { headers: headers })
.then(async (response) => {
let token = response.data.data;
sessionStorage.setItem("access-token", token);
originalRequest.headers["Authorization"] = token;
originalRequest.headers["grant_type"] = "grant_type";
return [null, await axios.request(originalRequest)];
})
.catch((err) => {
console.log(err);
alert("blablabla.");
return [err, null];
});
// Handle here
if(secondError) {
return Promise.reject(secondError);
}
return Promise.resolve(res)
}
return Promise.reject(error);
}
);
The above solution worked for me perfectly. here's the modified code that I used for my requirement.
export default function axiosInterceptor() {
//Add a response interceptor
axios.interceptors.response.use(
(res) => {
// Add configurations here
return res;
},
async function (error) {
const originalRequest = error.config;
let secondError, res
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
[secondError, res] = await axios({
method: "POST",
url: `${baseURL}/account/token/refreshtoken`,
withCredentials: true,
headers: { "Content-Type": "application/json" },
})
.then(async (response) => {
//handle success
return [null, await axios.request(originalRequest)];
}).catch(function (error) {
console.error(error)
});
}
if (secondError) {
return Promise.reject(secondError);
}
return Promise.resolve(res)
}
);
}

Pusher - with Wix HTTP Functions

I am trying to integrate Pusher with the Wix HTTP Functions
For example:
A GET request is made to the Wix site ( path: '/findItems' ). After the request is made, I want to check for new insertion of items in the database. This, I found, I could do with the afterInsert hook. When the hook is hooked, I want to trigger the Pusher.
This is the code I am currently using http-functions.js:
import { ok, created, notFound, serverError } from 'wix-http-functions';
import wixData from 'wix-data';
import Pusher from "pusher";
const pusher = new Pusher({
appId: "xxxxx",
key: "xxxxxxxxxxxxxxx",
secret: "xxxxxxxxxxxx",
cluster: "xxxx",
useTLS: true
});
export function get_findItems(request) {
let options = {
"headers": {
"Content-Type": "application/json"
}
};
return wixData.query("users")
.eq("firstName", request.path[0])
.eq("lastName", request.path[1])
.find()
.then((results) => {
if (results.items.length > 0) {
options.body = {
"items": results.items
};
return ok(options);
}
options.body = {
"error": `'${request.path[0]} ${request.path[1]}' was not found`
};
return notFound(options);
})
.catch((error) => {
options.body = {
"error": error
};
return serverError(options);
});
}
export function post_newItem(request) {
let options = {
"headers": {
"Content-Type": "application/json"
}
};
return request.body.text()
.then( (body) => {
return wixData.insert("users", JSON.parse(body));
} )
.then( (results) => {
options.body = {
"inserted": results
};
return created(options);
} )
.catch( (error) => {
options.body = {
"error": error
};
return serverError(options);
} );
}
export function users_afterInsert(item, context) {
let hookContext = context;
pusher.trigger("channel", "action", {
firstName: item.firstName,
lastName: item.lastName
});
return item;
}
But unfortunately, Pusher does not get triggered. After Debugging, I found that the Pusher package is installed and working but not triggering only in the afterInsert hook!
Any help is greatly appreciated!
Thanks !
The code for the afterInsert hook needs to be in a backend file named data.js, not in the http-functions.js file as you have it now.

Stripe auth and capture charge with NODE.js

I'm having trouble with the pre-authorization described here https://stripe.com/docs/charges#auth-capture.
The auth goes successful (capture params to false), I can store the ID of the carghe on my databse and I can see the uncaptured charge from my Stripe Dashboard.
Problem comes when I try to capture the charge, because it fails with Error: No such charge: <CHARGE_ID>.
Here is the code:
constructor(){
this.stripe = require('stripe')('<sk_test_mysecretkey>');
}
async captureCharge(chargeId) {
try {
/**
* https://stripe.com/docs/api/charges/capture
*/
return this.stripe.charges.capture(chargeId)
.then((charge) => {
return {
error: false,
success: true,
message: 'ChargeSuccesful',
code: 200,
charge: charge,
};
},
(err) => {
console.log("CAPTURE CHARGE ERROR: ", err);
return {
success: false,
error: err.type,
code: err.statusCode,
};
}
);
} catch (e) {
console.log('ERROR CAPTURE', e);
}
}
Even if I try with a POST to https://api.stripe.com/v1/charges/<CHARGE_ID>/capture with auth: Bearer <sk_test_mysecretkey> i get the same error:
{
"error": {
"code": "resource_missing",
"doc_url": "https://stripe.com/docs/error-codes/resource-missing",
"message": "No such charge: <CHARGE_ID>",
"param": "charge",
"type": "invalid_request_error"
}
}
The uncaptured charge still exist on Stripe.
Thanks in advance.
UPDATE
I forgot to say that the charge isn't a simple charge, but it is a split payment with a shared customer. Stripe supports three approaches for processing split payment, I have choosed the direct charges:
async authorizationCharge(amount, merchantStripeId, billId, customerId) {
try {
var fee = 0.25;
/** Pre-Authorization Charge using a shared customer
* https://stripe.com/docs/charges#auth-capture
* https://stripe.com/docs/connect/shared-customers
*/
return this.stripe.tokens
.create(
{ customer: customerId },
{ stripe_account: merchantStripeId }
)
.then((oneTimeToken) => {
return this.stripe.charges
.create(
{
amount: Math.round(amount),
currency: 'eur',
application_fee: fee,
description: 'Bill ID: ' + billId,
source: oneTimeToken.id,
capture: false,
},
{ stripe_account: merchantStripeId }
)
.then((charge) => {
console.log('CHARGE: ', charge);
return {
error: false,
success: true,
code: 200,
charge: charge,
fee: fee,
};
},
(err) => {
// ERROR INFO:
// https://stripe.com/docs/api#error_handling
console.log('ERROR', err);
return {
success: false,
error: err.type,
code: err.statusCode,
};
}
);
},
(err) => {
// ERROR INFO:
// https://stripe.com/docs/api#error_handling
console.log('ERROR', err);
return { success: false, error: err.type, code: err.statusCode };
}
);
} catch (e) {
console.log(e);
}
}
Finally I understood the reason, I did not indicate the connected account (see the updated question).
return this.stripe.charges.capture(chargeId, { stripe_account: merchantStripeId }) <---- CONNECTED ACCOUNT
.then((charge) => {
...
}

Resources