Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

node.js - How to connect Express backend and Next.js frontend?

I modified my server.js(by looking at Vercel site)

connectDB();
const routes = require('./routes');
const blogpost = require('./routes/blogpost');
const auth = require('./routes/auth');
const users = require('./routes/users');
const comments = require('./routes/comments');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = routes.getRequestHandler(app);

app.prepare()
    .then(() => {
        const server = express();
        server.use(handler);
        server.use(express.json());
        server.use(cookieParser());
        server.use(mongoSanitize());
        server.use(helmet());
        server.use(xss());

        if (process.env.NODE_ENV === 'development') {
            server.use(morgan('dev'));
        }

        const limiter = rateLimit({
            windowMs: 10 * 60 * 1000,
            max: 100,
        });
        server.use(limiter);

        server.use(hpp());

        server.use(cors());

        server.use('/api/v1/auth', auth);
        server.use('/api/v1/blogpost', blogpost);
        server.use('/api/v1/users', users);
        server.use('/api/v1/comments', comments);

        const PORT = process.env.PORT || 5000;

        server.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));
    });

Backend and frontend are separate folders,so I figured out that concurrently help me solve this.

My package.json

  "scripts": {
    "start": "node server",
    "client": "cd ..//frontend && npm run dev",
    "server": "nodemon server",
    "dev": "concurrently --kill-others-on-fail "npm run client" "npm run server"",
    "test": "jest"
  },

I got error

internal/modules/cjs/loader.js:1083
[1]   throw err;
[1]   ^
[1] 
[1] Error: Cannot find module 'react'
[1] Require stack:
[1] - /home/jholmes/blog_mongo/backend/node_modules/next/dist/next-server/server/render.js
[1] - /home/jholmes/blog_mongo/backend/node_modules/next/dist/next-server/server/nextserver.js

 [nodemon] app crashed - waiting for file changes before starting...
[0] ready - started server on http://localhost:3000
[0] event - compiled successfully

I can signup at the frontend but no data is passed to the backend. What is wrong with my configuration?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From your explanation and package.json file, it seems you were creating a microservices application where the backend standalone from the frontend.

But your server.js file shows that you were creating a monolithic application where the frontend and backend is on the same instance. The error message explains that to do Server Side Rendering (SSR), it needs reactjs library to render the frontend, unfortunately couldn't find reactjs because your backend supposed to not having reactjs.

If you want to create microservices application, then the way frontend connect to backend is via APIs. If you tend to have monolithic application, then you need to read the SSR documentation of NextJS.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...