在API端口而不是客户端上反应服务器端呈现

时间:2017-07-04 18:08:11

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

我有一个使用快速API构建的反应应用程序与mongoDB交互。我现在正尝试在server.js文件中设置服务器端呈现。我无法弄清楚为什么,但服务器呈现的字符串仅通过我的API端口localhost:3899/api在浏览器中发送,而不是我的客户端所在的localhost:3000

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

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

  • node_modules
  • 反应的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!' });
    });
  });

非常感谢任何指导。

2 个答案:

答案 0 :(得分:0)

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

PORT=3000 node server.js

您的代码中还有其他问题。您已定义路由器并通过定义/api来安装路由器app.use('/api', router)。因此,只要您访问http://localhost:3000,就会获得404

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

答案 1 :(得分:0)

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

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