Next.js Discord

Discord Forum

Cors Error

Answered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
error message in picture
route handle :
export async function POST(req: NextRequest ) {
    try {
        console.log("post is called")
        console.log(req)
        const data = await req.json()
        console.log(data)
        const Irys = await getIrys()
        const tx = await Irys.upload(JSON.stringify(data), {
        tags: [{ name: 'Content-Type', value: 'application/json' }],
        })
        return Response.json({
            url: `https://arweave.net/${tx.id}`,
            state : 200,
            
        })
    } catch (error) {
        console.log(error)
    }
}

request is
async function uploadJson(data: TextOnlyMetadata) {
    try {
      console.log("before fetch")
      const body = JSON.stringify(data)
      console.log(body)
      const response = await fetch('/api/upload', {
        method: 'POST',
        headers: {
            "Content-Type": "application/json",
        },
        body : body
      })
      console.log(response)
      console.log("before response.json")
      return response.url
    } catch(err) {
      console.log(err)
    }
}

i read docs and try set next.config.js but it not works
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
    async headers() {
        return [
            {
                // matching all API routes
                source: "/api/:path*",
                headers: [
                    { key: "Access-Control-Allow-Credentials", value: "true" },
                    { key: "Access-Control-Allow-Origin", value: "*" }, // replace this your actual origin
                    { key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
                    { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
                ]
            }
        ]
    }
}

module.exports = nextConfig
Answered by Anay-208
You have to use cors header because you are accessing from different origin
View full answer

16 Replies

Northeast Congo LionOP
add some information
need anyone help
lemme see
You have to use cors header because you are accessing from different origin
Answer
@Northeast Congo Lion
Northeast Congo LionOP
@Anay-208 thank you for your reply. how to add header to my return response.json()
Another question is why these configurations I'm trying to add in next.config.js don't work?
Hey @Northeast Congo Lion, I'm awaiting a reply on your end regarding this issue.
If your issue is resolved, you can ignore this message and I'll assume your issue is resolved!
Northeast Congo LionOP
@Anay-208 sorry i forget reply to set issue is resolved after i fix it🥺
@Anay-208 https://nextjs.org/docs/app/building-your-application/routing/route-handlers#cors
mark this message as a solution @Northeast Congo Lion