【问题标题】:express-typescript-react: Send a json response after sending the view from the same requestexpress-typescript-react:从同一请求发送视图后发送 json 响应
【发布时间】:2026-01-10 19:20:06
【问题描述】:

以下是我用打字稿编写的简单快速服务器的代码。

import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';
import fs from 'fs';
import { DISTDIR } from './shared/constants';
import LoginController from './controllers/login';
// import * as test from '../../helpers/util';

function name() {
  return {
    name: 'Amaan'
  };
}
class App {
  public express: express.Application;

  constructor() {
    this.express = express();
    this.middleware();
    this.routes();
  }
  private middleware(): void {
    this.express.use(function(req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Headers', '*');
      next();
    });
    this.express.use(bodyParser.json());
    this.express.use(bodyParser.urlencoded({ extended: false }));
  }
  private routes(): void {
    this.express.get('/', function(req, res) {
      res.sendFile(path.join(projectDir, 'dist', 'index.html'));
    });
  }
}
export default new App().express;

正如您在此处看到的,我正在发回包含我的 React 代码的 index.html

this.express.get('/', function(req, res) {
  res.sendFile(path.join(projectDir, 'dist', 'index.html'));
});

现在我面临一个问题,我需要从该请求中的任何 API 发送响应。像这样的:

function name() {
  return {
    name: 'Amaan'
  };
}

private routes(): void {
  this.express.get('/', function(_, res) {
  res.setHeader('Content-type', 'text/html');
  fs.readFile(path.resolve(DISTDIR, 'index.html'), null, (err, data) => {
    if (err) {
      res.writeHead(404);
      res.write('Not found');
    } else {
      res.write(data);
    }
    res.setHeader('Content-type', 'text/json');
    res.send(name());
    res.end();
  });
});

这给了我一个'Can\'t set headers after they are sent.' 错误。

请告诉我,如何将 json 响应与视图一起发送。

【问题讨论】:

    标签: node.js reactjs typescript express webpack


    【解决方案1】:

    做了一些研究,发现这种安排非常紧密耦合,是的,我们不能为每个请求发送多个响应。不用说,我使用webpack-dev-server 启动前端并从 express 代码中删除了中间件。

    【讨论】:

      【解决方案2】:

      一个请求一个响应。如果您在应用初始化时需要一些东西,请使用 onLoad 函数发出另一个请求。

      【讨论】:

        【解决方案3】:

        我认为您不能在一个响应中发送 HTML 文件后发送 json。你可以让一个 React 组件发送另一个请求来获取数据。

        【讨论】:

          最近更新 更多