Home > Mobile >  How to make a request from front end to backend in custom next.js express server
How to make a request from front end to backend in custom next.js express server

Time:04-25

I am trying to configure a next.js app with custom express.js server. I have configured the server and it runs but, I cannot make a request to this server from front-end.

Below is the server.js code.

import "@babel/polyfill";
import next from "next";
import "@babel/polyfill";
import dotenv from "dotenv";
import express from 'express';

const port = 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });

const handle = app.getRequestHandler();

// preparing next.js server 

app.prepare().then(() => {
     const server = express();

     server.get('*', ( req, res ) => {
         return handle(req, res);
     })

     server.get('/api/test', ( req, res ) => {
         res.send({john: john, doe: doe});
     })

     server.listen( port, err => {
         if (err) throw err
         console.log(`Server started at port ${port}`); 
     })
}).catch(ex => {
    console.error(ex.stack);
    process.exit(1);
})

Below is the react front-end code.

import { useEffect } from 'react';
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'

export default function Home() {

  useEffect(() => {
      const fetchUrl = "/api/test";
      const method = "GET";
        fetch(fetchUrl, {
          method: method,
        })
          .then((response) => response.json())
          .then((json) => {
            console.log(json);
          });  
  },[])


  return (
    <div className={styles.container}>
     
    </div>
  )
}

I keep getting error saying, 404 localhost:3000/api/test not found

CodePudding user response:

I think if you create the custom server, you had to use this package next-routes (I have not used it for a long time) to register the routes. For example, in routes.js

const routes = (module.exports = require("next-routes")());

routes
  .add("nameTest", "/api/test")

then import routes to server.js

const routes = require("../routes");
const app = next({ dev });
const handle = routes.getRequestHandler(app);

CodePudding user response:

By default, your Next.js frontend will look for a file inside pages/api whenever a route that begins with /api is requested. Since your Express routes begin with /api, you can setup rewrites() in your next.config.js to map incoming requests to your Express routes instead:

const nextConfig = {
  // override `pages/api`
  async rewrites() {
    return [
      {
        source: "/api/:path*",
        destination: "http://localhost:3000/api/:path*",
      },
    ];
  },
};

module.exports = nextConfig;
  • Related