You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中getInitialProps服务端渲染首次/刷新时失效求助

Fixing Next.js getInitialProps POST Request Failure in SSR

Alright, let's break down why your getInitialProps is failing during server-side rendering (SSR) or page refreshes, and walk through how to fix it.

The Core Problem

When getInitialProps runs on the server (like on first load or page refresh), it’s executing in a Node.js environment—not the browser. That relative path /user in your axios.post('/user') doesn’t resolve to your frontend’s domain the way it does in the browser. Instead, Node will try to send the request to the server’s own local address (e.g., http://localhost:3000/user if your Next.js app runs on port 3000), which almost certainly isn’t pointing to your Express backend. That’s why your Express server never receives the request, and you end up hitting the error case printing 4444.

Step-by-Step Fixes

1. Use Absolute Paths for Server-Side Requests

You need to tell axios to use your Express backend’s full URL when running on the server. Here’s how to adjust your code:

First, create a reusable axios instance that handles client/server differences:

import axios from 'axios';

// Create an axios client with dynamic base URL
const apiClient = axios.create({
  baseURL: typeof window === 'undefined' 
    ? 'http://localhost:YOUR_EXPRESS_PORT' // Replace with your Express backend's full URL
    : '', // On the client, relative paths work as expected
});

Home.getInitialProps = async ({ store }) => {
  try {
    // Use the configured apiClient instead of raw axios
    const res = await apiClient.post('/user');
    const user = res.data;
    store.dispatch(setLoggingState(user));
  } catch (err) {
    console.log('Request failed:', err);
    // Add additional error handling here if needed
  }
  return {};
};

2. Set Up an API Proxy (Alternative Approach)

If you prefer sticking with relative paths, you can configure Next.js to proxy requests to your Express backend. Create or update next.config.js:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/user', // Match the relative path in your request
        destination: 'http://localhost:YOUR_EXPRESS_PORT/user', // Redirect to your Express endpoint
      },
      // Add more routes here if you have other API calls
    ];
  },
};

Restart your Next.js dev server after adding this—now both client and server-side requests to /user will route directly to your Express backend.

3. Verify CORS Settings on Your Express Backend

If your Express backend runs on a different port or domain than Next.js, you’ll need to configure CORS to allow requests from your Next.js server. Install the cors package and add it to your Express app:

const cors = require('cors');
const express = require('express');
const app = express();

// Allow requests from your Next.js app's URL
app.use(cors({ origin: 'http://localhost:3000' })); // Replace with your Next.js app's URL

// Rest of your Express route setup...

Quick Note on Async/Await

Your original code uses .then()/.catch() inside an async function but doesn’t await the axios promise. Switching to try/catch with await makes the code cleaner and ensures all asynchronous operations finish before getInitialProps returns.

内容的提问来源于stack exchange,提问作者travellingkite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:08:41