Official Solution

Next.js API Routes

Next. Js 9.0+ provides Mock data, and Mock routing rules are basically the same as page routing rules.

  1. Create a new folder called Pages/API (the name cannot be changed), where all mock files will be stored and will not be written to the page routing list when you package

  2. Mock file pages/ API /init.js (ts also supported)

    // export a request handler function instead of a React Component
    export default function handle(req, res) {
        // Returns non-JSON data
        // res.end('Hello World')
    
        // Returns json data
        res.json({
            code: 0.msg: 'Success'.data: {
                countryCode: 'US'.currencyName: 'USD'}})}Copy the code
  3. To access the url http://localhost:3000/en/api/init, can see the returned json data.

Simulation of delay

import delay from '@/utils/delay';

export default async function handle(req, res) {
    await delay(3000); // The parameter is the time to delay
    res.json({});
}
Copy the code

utils/delay.ts

/** * Wait time ends * @param ms Wait milliseconds */
export default function delay(ms: number) :Promise<void> {
    return new Promise((resolve) = >{ setTimeout(resolve, ms); })}Copy the code