gcui-art/suno-api

Cors issue

Closed this issue · 0 comments

const handleSubmit = () => {
        const options = {
            method: 'POST',
            credentials: 'include',
            headers: {
            'Content-Type': 'application/json', 
            },
            body: JSON.stringify(selections),
        };
    fetch('http://localhost:3030/api/generate', options)
        .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
        })
        .then(data => {
        console.log('Success:', data); 
        })
        .catch((error) => {
        console.error('Error:', error); 
        });
    };
Im trying to use api/generate endpoint. 
But there is Cors Error. 

Access to fetch at 'http://localhost:3030/api/generate' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


So i add "Access-Control-Allow-Origin": "*"  this in src/app/api/generate/route.ts  

like this 
export async function POST(req: NextRequest) {
 if (req.method === 'OPTIONS') {
  
   return new Response(null, {
     headers: {
       "Access-Control-Allow-Origin": "*", 
       "Access-Control-Allow-Methods": "POST, OPTIONS",
       "Access-Control-Allow-Headers": "Content-Type, Authorization",
     },
   });
 }

 if (req.method === 'POST') {
   try {
     const body = await req.json();
     const { prompt, make_instrumental, wait_audio } = body;

     if (!prompt) {
       return new NextResponse(JSON.stringify({ error: 'Prompt is required' }), {
         status: 400,
         headers: { 'Content-Type': 'application/json' }
       });
     }

     const audioInfo = await (await sunoApi).generate(prompt, make_instrumental == true, wait_audio == true);
     logger.info("check audio Info" , audioInfo);
     return new NextResponse(JSON.stringify(audioInfo), {
       status: 200,
       headers: { 'Content-Type': 'application/json',"Access-Control-Allow-Origin": "*" }
     });
   }
   But still there is cors error. 
-------------------------------------------------------------------------------------

image
This photo is from Network Headers In General