简体   繁体   English

NextJS:从 CORS 政策阻止的来源访问 XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”header

[英]NextJS: Access to XMLHttpRequest from origin blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I was working on a NFT marketplace app using NextJS as frontend and Solidity as backend.我正在开发一个 NFT 市场应用程序,使用 NextJS 作为前端,使用 Solidity 作为后端。 When I tried to sell an NFT using the frontend UI, I encountered this error:当我尝试使用前端 UI 出售 NFT 时,我遇到了这个错误:

Access to XMLHttpRequest at 'https://gateway.pinata.cloud/ipfs/QmbbWLfoPg9aSpFCKoYQRadQynmCRMjydVhkXJZKBXKnyT' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my code:这是我的代码:

import {useState} from 'react';
import {ethers} from 'ethers';
import {useRouter} from 'next/router';
import Web3Modal from 'web3modal';
import {contractAddress, INFURA_URL, PINATA_KEY, PINATA_SECRET} from '../config.js';
import NFTMarketplace from "../abi/NFTMarketplace.json";
import axios from 'axios';
import Image from 'next/image';

export default function createNFT() {
    const [fileURL, setFileURL] = useState(null);
    const [formInput, updateFormInput] = useState({price: "", name: "", description: ""});
    const router = useRouter();
    const [loadingState, setLoadingState] = useState('Not loaded');

    // upload image to IPFS
    async function imageUpload(e) {
        const file = e.target.files[0];
        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': PINATA_KEY,
                    'pinata_secret_api_key': PINATA_SECRET,
                    'Content-Type': 'multipart/form-data'
                }
            });

            const imageURL = `https://gateway.pinata.cloud/ipfs/${
                resFile.data.IpfsHash
            }`;
            setFileURL(imageURL)

        } catch (e) {
            console.log(e)
        }
    }

    // upload metadata to IPFS and return URL to use in later transaction
    async function uploadToIPFS() {
        const {name, description, price} = formInput;
        if (!name || !description || !price || !fileURL) {
            return
        }
        setLoadingState('Loading...')

        try {
            let jsonData = JSON.stringify({
                "pinataMetadata": {
                    "name": `${
                        name.json
                    }`
                },
                "pinataContent": {
                    name,
                    description,
                    image: fileURL
                }
            })

            const resFile = await axios({
                method: "post",
                url: "https://api.pinata.cloud/pinning/pinJSONToIPFS",
                data: jsonData,
                headers: {
                    'pinata_api_key': PINATA_KEY,
                    'pinata_secret_api_key': PINATA_SECRET,
                    'Content-Type': 'application/json'
                }
            });

            const tokenURI = `https://gateway.pinata.cloud/ipfs/${
                resFile.data.IpfsHash
            }`;
            return tokenURI;
        } catch (error) {
            console.log("Error uploading file: ", error);
        }
    }

    async function listNFTForSale() {
        const tokenURI = await uploadToIPFS();
        const web3modal = new Web3Modal();
        const connection = await web3modal.connect();
        const provider = new ethers.providers.Web3Provider(connection);
        const getnetwork = await provider.getNetwork();
        const goerliChainId = 5;
        if (getnetwork.chainId != goerliChainId) {
            alert("You are not connected to the Goerli network!")
            return;
        }
        // sign the transaction
        const signer = provider.getSigner();
        const contract = new ethers.Contract(contractAddress, NFTMarketplace.abi, signer);
        const price = ethers.utils.parseUnits(formInput.price, 'ether');
        let listingPrice = await contract.getListingPrice();
        listingPrice = listingPrice.toString();
        let transaction = await contract.createToken(tokenURI, price, {value: listingPrice});
        await transaction.wait();
        router.push('/');
    }
    return (<div className='flex justify-center'>
        <div className='w-1/8 flex-col mr-10 mt-10'> {
            !fileURL && (<Image className='rounded mt-4' src='/image_place_holder.jpg' alt="Image placeholder" width={300} height={200}/>)
        }
            {
            fileURL && (<Image src={fileURL} alt="Image uploaded successfully" className='rounded mt-4' placeholder="blur" blurDataURL="/image_place_holder.jpg" width={300} height={200}/>)
        }</div>
        <div className='w-1/2 flex flex-col'>
            <input placeholder='Asset Name' className='mt-8 border rounded p-4' onChange={e=>updateFormInput({...formInput, name: e.target.value})}/>
            <textarea placeholder='Asset Description' className='mt-2 border rounded p-4' onChange={e=>updateFormInput({...formInput, description: e.target.value})}/>
            <input placeholder='Asset Price in Ethers' className='mt-2 border rounded p-4' type="number" onChange={e=>updateFormInput({...formInput, price: e.target.value})}/>
            <input type="file" name="Asset" className='my-4' onChange={imageUpload} /> {
            fileURL && (<button onClick={listNFTForSale} className="font-bold mt-4 bg-pink-500 text-white rounded p-4 shadow-lg"> {
                loadingState == 'Not loaded' ? 'Create NFT' : 'Uploading...'
            } </button>)
        } </div>
    </div>)
}

I don't have enough reputation so I can only provide links of images.我没有足够的声誉,所以我只能提供图片链接。

Unhandled Runtime Error on UI UI 上未处理的运行时错误

NFT Sell Page UI NFT 销售页面 UI

The error occurring on the Unhandled Runtime Error is:未处理的运行时错误发生的错误是:

Unhandled Runtime Error
AxiosError: Network Error

Call Stack
XMLHttpRequest.handleError
node_modules/axios/lib/adapters/xhr.js (154:0)

I tried installing the Access-Control-Allow-Origin extension on Chrome, but it doesn't work.我尝试在 Chrome 上安装Access-Control-Allow-Origin扩展程序,但它不起作用。 Other approaches suggested usually work with ExpressJS and NodeJS but I'm working with NextJS.建议的其他方法通常适用于 ExpressJS 和 NodeJS,但我正在使用 NextJS。 How do I resolve this?我该如何解决这个问题?

I've encountered same problem and adding below to axios request headers solved my issue.我遇到了同样的问题,将以下内容添加到 axios 请求标头解决了我的问题。 I am not sure which request you are getting the error but you can expand the error in console, it should tell the file/line that generates the error.我不确定您收到的错误是哪个请求,但您可以在控制台中扩展错误,它应该告诉生成错误的文件/行。

'Accept': 'text/plain'

For example:例如:

const resFile = await axios({
            method: "post",
            url: "https://api.pinata.cloud/pinning/pinFileToIPFS",
            data: formData,
            headers: {
                'Accept': 'text/plain',
                'pinata_api_key': PINATA_KEY,
                'pinata_secret_api_key': PINATA_SECRET,
                'Content-Type': 'multipart/form-data'
            }
        });

More on: https://knowledge.pinata.cloud/en/articles/6848516-how-to-fix-400-errors-with-dedicated-gateways更多信息: https://knowledge.pinata.cloud/en/articles/6848516-how-to-fix-400-errors-with-dedicated-gateways

and

https://stackoverflow.com/a/35553666/18100033 https://stackoverflow.com/a/35553666/18100033

Hope that helps.希望有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 来自源的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头 - XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS 策略已阻止从原点 '' 访问 XMLHttpRequest - Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present 对 XMLHttpRequest 的访问已被 CORS 策略阻止 请求的资源上不存在“Access-Control-Allow-Origin”标头 - react Access to XMLHttpRequest has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource CORS 策略阻止了对获取的访问:请求的资源上不存在“Access-Control-Allow-Origin”header - Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource 来源&#39;http:// localhost:3000&#39;中的&#39;已被CORS策略阻止:所请求的资源上没有&#39;Access-Control-Allow-Origin&#39;标头 - ' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource React 组件已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header - React component has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS 政策阻止了获取“url”的访问:请求的资源上不存在“Access-Control-Allow-Origin”header。 ReactJS - Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS CORS - 没有'Access-Control-Allow-Origin' header 存在于请求的资源上 - CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource “http://localhost:3000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头 - 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource .NET 核心 webapp 服务 SPA:被 CORS 策略阻止:没有“Access-Control-Allow-Origin” header 出现在请求的资源上 - .NET Core webapp serving SPA: Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM