I have created an NFT function using Pinata. With My code, I can upload images to Pinata, but when I add metadata and call create-NFT function, I always facing ERR_BAD_REQUEST: 400 Bad Request (as below picture)
Do you know how to solve this error? I have already checked the API Key and the Secret Key is correct.
Here is my code:
- uploadToIPFS function:
//@dev: Upload to IPFS function
const uploadToIPFS = async (file) => {
if (file) {
try {
const formData = new FormData();
formData.append("file", file);
const resFile = await axios({
method: "post",
url: "https://api.pinata.cloud/pinning/pinFileToIPFS",
data: formData,
headers: {
pinata_api_key: key,
pinata_secret_key: secret_key,
"Content-Type": `multipart/form-data`,
Authorization: `Bearer ${pinata_JWT}`,
},
});
const imgHash = `https://gateway.pinata.cloud/ipfs/${resFile.data.IpfsHash}`;
console.log(imgHash);
return imgHash;
} catch (error) {
console.log("Error while uploading to IPFS", error);
}
}
};
- createNFT function
//@dev: Create NFT function
const createNFT = async (name, price, image, description, router) => {
if (!name || !description || !price || !image) {
console.log("Data Is Missing");
return;
}
const data = JSON.stringify({ name, description, image });
try {
const resFile = await axios({
method: "POST",
url: "https://api.pinata.cloud/pinning/pinFileToIPFS",
data: data,
headers: {
pinata_api_key: key,
pinata_secret_key: secret_key,
"Content-Type": `application/json`,
Authorization: `Bearer ${pinata_JWT}`,
},
});
// Upload image file to Pinata IPFS
const imgHash = `https://gateway.pinata.cloud/ipfs/${resFile.data.IpfsHash}`;
console.log(imgHash);
await createSale(imgHash, price);
router.push("/searchPage");
} catch (error) {
console.log("Error while creating NFT:", error);
}
};
- createSale function
//@dev: createSale function
const createSale = async (url, formInputPrice, isReselling, id) => {
try {
console.log(url, formInputPrice, isReselling, id);
const price = ethers.utils.parseUnits(formInputPrice, "ether");
const contract = await connectingWithSmartContract();
const listingPrice = await contract.getListingPrice();
const transaction = !isReselling
? await contract.createToken(url, price, {
value: listingPrice.toString(),
})
: await contract.reSellToken(url, price, {
value: listingPrice.toString(),
});
await transaction.wait();
console.log(transaction);
} catch (error) {
console.log("Error while creating sale");
}
};
I followed to youtube: https://www.youtube.com/watch?v=w3IsLQxXTvo&t=561s
Do you know how to solve this error? I have already checked the API Key and the Secret Key is correct. And my code can upload NFT images to Pinata. But when calling the create-NFT function, this error happens.
I have update my code with below and it working fine. The reason Request invalid because the API Pinata in below is not valid for JSON file added.
My code after update: