Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
How to make a request from front end to backend in custom next.js express server

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

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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);
over 4 years ago · Santiago Trujillo Relatório

0

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;
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda