admin管理员组

文章数量:1327976

I try to fetch the data from database using mysql in next.js using API routes functionality But when I call the route they show me the this error

Blockquote Error: No response is returned from route handler

Here I can write code like below

import { NextResponse } from "next/server";
import db from '../../../../lib/db';

export function GET(request){
    db.query('SELECT * FROM department', (error, results, fields) => {
      if (error) {
        console.error('Error querying the database:', error);
        return NextResponse.json({ error: 'Internal Server Error' },{status:500});
      }

      return NextResponse.json({ data: results },{status:201});
    });
}

I try to fetch the data from database using mysql in next.js using API routes functionality But when I call the route they show me the this error

Blockquote Error: No response is returned from route handler

Here I can write code like below

import { NextResponse } from "next/server";
import db from '../../../../lib/db';

export function GET(request){
    db.query('SELECT * FROM department', (error, results, fields) => {
      if (error) {
        console.error('Error querying the database:', error);
        return NextResponse.json({ error: 'Internal Server Error' },{status:500});
      }

      return NextResponse.json({ data: results },{status:201});
    });
}

When I call this api in console it show me the message Connected to MySQL database successfully and then after it show the above error

Share Improve this question edited Nov 29, 2023 at 13:11 Shark asked Nov 28, 2023 at 6:28 SharkShark 1761 gold badge1 silver badge9 bronze badges 2
  • Which error? You didn't include the error message in your question. – RoToRa Commented Nov 28, 2023 at 11:26
  • Error: No response is returned from route handler This error show me in terminal – Shark Commented Nov 29, 2023 at 13:08
Add a ment  | 

1 Answer 1

Reset to default 4

I think it issue could be in a code. In your code db.query function work as async manner and before your db query plete they return response. So you must used promises to solve the issue.

try {
    const results = await new Promise((resolve, reject) => {
      db.query('SELECT * FROM department', (error, results, fields) => {
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
      });
    });

    return NextResponse.json({ data: results }, { status: 201 });
  } catch (error) {
    return NextResponse.json({ error: error}, { status: 500 });
  }

本文标签: javascriptError No response is returned from route handler in nextjsStack Overflow