【问题标题】:React server side rendering on API port instead of client在 API 端口而不是客户端上反应服务器端渲染
【发布时间】:2017-12-08 06:42:48
【问题描述】:

我有一个使用 express API 构建的 react 应用程序来与 mongoDB 交互。我现在正尝试在我的server.js 文件中设置服务器端渲染。我不知道为什么,但服务器呈现的字符串仅通过我的 API 端口 localhost:3899/api 在浏览器中发送,而不是在为我的客户端提供服务的 localhost:3000 上发送。

当我 curl http://localhost:3899 时,我在控制台中获得了 html 字符串。当我curl http://localhost:3000 时,我得到了public/index.html 骨架。

我的客户端和服务器目录在同一级别上彼此相邻。

  • node_modules
  • react-ui
  • 服务器
  • ...

server.js:

import express from 'express';
import path from 'path';
import React from 'react';
import 'ignore-styles';
import ReactDOMServer from 'react-dom/server';
import render from './render';
import App from '../react-ui/src/App';
import mongoose from 'mongoose';
import cors from 'cors';
import bodyParser from 'body-parser';
import Appointment from './model/appointments';

//and create our instances
var app = express();
var router = express.Router();

app.use(express.static(path.resolve(__dirname, '../react-ui/build/static')));
//set our port to either a predetermined port number if you have set 
//it up, or 3899
var port = process.env.PORT || 3899;
//db config
mongoose.connect('mongodb://josh11:josh11@ds133162.mlab.com:33162/heroku_tl016m5d');
app.use(cors());
//now we should configure the API to use bodyParser and look for 
//JSON data in the request body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//now we can set the route path & initialize the API
router.get('/', function(request, response) {
  response.render(
    <!doctype html>
    <html>
        <header>
            <title>My Universal App</title>
        </header>
        <body>
            <div id='app'>${ReactDOMServer.renderToString(<App />)}</div>
            <script src='bundle.js'></script>
        </body>
    </html>
  );
});


//Use our router configuration when we call /api
app.use('/api', router);
//starts the server and listens for requests
app.listen(port, function() {
  console.log('api running on port' + port);
});
//adding the /appointments route to our /api router
router.route('/appointments')
  //retrieve all appointments from the database
  .get(function(request, response) {
    //looks at our Appointment Schema
    Appointment.find(function(error, appointments) {
      if (error)
        response.send(error);
      //responds with a json object of our database appointments.
      response.json(appointments)
    });
  })
  //post new appointment to the database
  .post(function(request, response) {
    var appointment = new Appointment();
    //body parser lets us use the req.body
    appointment.appointmentTitle = req.body.appointmentTitle;
    appointment.appointmentDate = req.body.appointmentDate;
    appointment.appointmentTime = req.body.appointmentTime;
    appointment.appointmentDescription = req.body.appointmentDescription;
    appointment.appointmentDestination = req.body.appointmentDestination;
    appointment.appointmentOrigin = req.body.appointmentOrigin;
    appointment.travelMode = req.body.travelMode;
    appointment.save(function(error) {
    if (error) 
      response.send(error);
      response.json({ message: 'Appointment successfully added!' });
    });
  });

任何指导将不胜感激。

【问题讨论】:

  • 你有环境变量PORT 吗?
  • 我为我的 API 设置了 var port = process.env.PORT || 3899;
  • 但是,您必须在执行程序之前设置环境变量。例如运行这个PORT=3000 node server.js
  • 当我运行它时,服务器在控制台中正常启动,除了我希望从命令中得到的端口 3000。但后来我的浏览器无法 GET/404 错误。我应该期待在那里发生什么?

标签: node.js reactjs express create-react-app server-side-rendering


【解决方案1】:

要在环境定义的端口上运行应用程序,请尝试

PORT=3000 node server.js

您的代码中还有其他问题。您已经定义了路由器并通过定义app.use('/api', router) 安装了路由器/api。因此,每当您访问 http://localhost:3000 时,您都会收到 404

要解决此问题,请将路由器挂载更改为 api.use('/', router)

【讨论】:

    【解决方案2】:

    您可以通过将 react-scripts 替换为 react-app-tools 来在同一端口上运行您的 API 和前端 - Create React App 的一个稍微改动的版本,增加了对服务器端代码的支持。

    在此处查找更多信息:https://github.com/kriasoft/react-app

    【讨论】:

      猜你喜欢
      • 2017-12-29
      • 2015-05-09
      • 2016-08-19
      • 2015-09-06
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多