Keep getting 422 unprocessable entity - node.js

Below is my code I keep getting error that it is unprocessable i looked it up and it said
to assign headers to content-type : "application/json" and i am still getting the errors.
export async function action({ request, params }) {
const data = await request.formData();
const eventData = {
title: data.get("title"),
Image: data.get("image"),
date: data.get("date"),
description: data.get("description"),
};
console.log(JSON.stringify(eventData));
const stringData = JSON.stringify(eventData);
const response = await fetch("http://localhost:8080/events", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: stringData,
});
console.log(response);
if (!response.ok) {
throw json({ message: "Could not save event" }, { status: 500 });
}
return redirect("/events");
}
it says server is expecting json and i have converted the data to json and still getting the error

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.'
}

React Expo: FileSystem.uploadAsync not sending request to the server instead throwing error

I am developing an app on react expo, and using Filesystem.uploadasync for file uploading and other data. But filesystem is not sending request to the server and throwing error "
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_context.t0.response.data')]". Below is my code
const addRequest = async (values, url) => {
try {
const user = await getData('user');
if (user != null) {
const token = user.Token;
const requestBody = {Branches: values.Branches, Color: values.Color, ImageInPOS: values.ImageInPOS, Name: values.Name, VisibilityInPOS: values.ImageInPOS}
console.log(requestBody);
console.log(values.Image.uri);
const result = await FileSystem.uploadAsync(`${BaseUrl}/${url}`, values.Image.uri, {
fieldName: 'Image',
httpMethod: "POST",
uploadType: FileSystemUploadType.MULTIPART,
parameters: requestBody,
headers: {
authorization: `Bearer ${token}`,
}
})
console.log(result);
return {
msg: result.data.msg,
status: result.status
};
}
else {
return;
}
}
catch (err) {
return {
msg: err.response.data.msg ? err.response.data.msg : "Something went wrong, Try Again",
status: err.response.status ? err.response.status : 500
};
}
}
I have cross checked my url, all imports but could not figure out what is going wrong.

Unable to Fetch Response - 201 Message [duplicate]

This question already has answers here:
how to get data from response from fetch javascript request
(2 answers)
Closed 6 months ago.
I am trying to retrieve a response from an API using fetch in NextJS, I can get the message by calling the API but am unable to get anything using fetch. All I get from fetch is response 201 message that it's created.
When I run the API in postman I get the response:
{
"id": "21a1f0a6-f6c4-4aaf-9f48-2c9dba276646",
"status": "SUBMITTED"
}
But when I call the API using fetch in NestJS I get the response:
Response { type: "cors", url: "http://localhost:9000/api/v1/fireblocks/createTxnVaultToVault", redirected: false, status: 201, ok: true, statusText: "Created", headers: Headers, body: ReadableStream, bodyUsed: false }
Expected Behavior
The expected behavior is to get the same response as the API postman response. I need the tracking id to be passed into the UI
Backend - API Service & Controller Code in NestJS
Below is the API to run a transaction, it's coming from a NodeJS like framework (NestJS):
async createTxnVaultToVault(txn: Txn) {
this.logger.log("Creating transaction for account: " + txn);
this.logger.log("Transaction data: " + JSON.stringify(txn));
const payload: TransactionArguments = {
assetId: txn.asset,
source: {
type: PeerType.VAULT_ACCOUNT,
id: String(txn.source)
},
destination: {
type: PeerType.VAULT_ACCOUNT,
id: String(txn.dest)
},
amount: String(txn.amount),
fee: String(txn.fee),
note: txn.note
};
this.logger.log("TXN Payload data: " + JSON.stringify(payload));
return fireblocks().createTransaction(payload)
.then(res => res)
.then(res => {
console.log(res)
return res;
})
.catch(err => {
console.log(err);
return err;
});
}
Below is the controller to run a transactions, it's coming from a NodeJS like framework (NestJS):
#ApiTags('Fireblocks Transactions - Create Vault to Vault Transaction')
#Post('/createTxnVaultToVault')
async createTxnVaultToVault(
#Body() txn: Txn
): Promise<any> {
return this.appService.createTxnVaultToVault(txn)
.catch(e => {
this.logger.log(e);
return getError(e);
});
}
Frontend - Fetch Code in NextJS
export async function transferFunds(txn) {
const req_url = process.env.NEXT_PUBLIC_FIREBLOCKS_SERVER + "/createTxnVaultToVault";
console.log(txn);
return fetch(req_url, {
method: 'POST',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(txn)
})
.then(resp => {
console.log(resp);
})
.then(resp => {
console.log(resp);
return resp;
})
.catch(err => {
console.log(err);
});
}
It worked by changing how the UI received data. Below is how the API should be called:
Frontend - Fetch Code in NextJS
export async function transferFunds(txn) {
const req_url = process.env.NEXT_PUBLIC_FIREBLOCKS_SERVER + "/createTxnVaultToVault";
console.log(txn);
return fetch(req_url, {
method: 'POST',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(txn)
})
.then( async resp => {
//console.log(await resp.json())
return await resp.json();
})
.then(data => {
console.log(data);
return data;
//return data;
});
}

How to post a body correctly in Postman

I try to make a post request to an api but, api returns error. Although I thought about it for a long time, I could not find the cause of the error.
I think the error is due to not creating the body correctly because when I send empty array as items array the code works.
API DOCUMENTATION:
Here is my request:
module.exports.createOrder = (token, paymentId, items, callback) => {
const url = urlBase;
request(
{
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
Authorization: `Bearer ${token}`,
},
body: {
secretKey: `${secretKey}`,
paymentId: paymentId,
items: items,
},
},
(error, response) => {
if (error) {
Sentry.captureException(error);
callback(errMessage, undefined);
} else {
const data = response.body;
callback(undefined, data);
}
}
);
};
Here is test values:
const testToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyM2RmYjg4NDA4M2IwMDAyNDNjYzRhNyIsImlhdCI6MTY0ODIyOTI1NywiZXhwIjoxNjQ4MzE1NjU3fQ.9fgR3ei81vsHVMhSi8VwEyE2WMgFIMthm0PF9_zrqjw"
const paymentId = "pi_1Dq2f62eZvKYlo2Cy1moIb0G"
const variant = {
variations_values: {
color:'Black',
size:'42'
},
price:495,
product_id: "883360511078"
}
const productId = "82936941"
const quantity = 1
const item = {
variant:variant,
productId:productId,
quantity:quantity
}
let items = [item]
orderRequests.createOrder(testToken, paymentId, items, (err, data) => {
if(data){
console.log(data)
} else{
console.log(err)
}
})
I get internal server error as a response when I post these test values, but If I post an empty array as items, api does not return internal server error. What is the problem, any help?
Internal Server Error Response when I send an array with post body:
Expected request when I send an empty array with post body:

Why the FormData is blank in react native

Why when I do a console.log(), just after the last form.append("","") work well I see what I push in them, and than when I watch on the backend is blanked ?
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client this error occured when I adding "Content-Type": "multipart/form-data" on the headers , do you know what happended ???
const uri = pictureUri.uri;
const uriParts = uri.split(".");
const fileType = uriParts[1];
const form = new FormData();
form.append("categorie","someCategorieInthere");
form.append("picture", {
uri,
name: `picture.${fileType}`,
type: `image/${fileType}`,
});
const handlSubmit = async () => {
try {
await axios.put("blablbla_url",
form,
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}
);
} catch (error) {
console.log({ message: error });
}
};

Resources