【问题标题】:How to deploy reactJS app with json-server如何使用 json-server 部署 reactJS 应用程序
【发布时间】:2020-11-17 05:16:48
【问题描述】:

我实际上已经通过以下方式部署了我的 React-app:-

  1. 运行命令:npm run build
  2. 已经有带有虚拟数据的 db.json 文件。 上下文,当我跑步时 json-server --watch db.json -p 3001 -d 2000 整个 react-app 在 localhost 上运行
  3. 使用 npm 安装 json-server
  4. 创建了一个 server.js 文件
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3001;

server.use(middlewares);
server.use(router);

server.listen(port);
  1. 在heroku上创建了应用并推送给heroku master 出于某种原因,该网站仅在我在本地计算机上运行 node server.js 并且它正在向我的本地端口发出请求时才有效。 如果该命令未运行,则 react-app 无法向数据库执行 axios 请求。 我不知道出了什么问题。 我为此使用了以下教程:https://github.com/jesperorb/json-server-heroku

我怀疑在我的代码中我创建了一个 basUrl.js 文件,其中

export const baseUrl = 'http://localhost:3001/';

我应该如何改变它来解决我的问题?

感谢您的帮助。

【问题讨论】:

    标签: node.js json reactjs heroku json-server


    【解决方案1】:

    你应该链接你用服务器(server.js)构建的 react 文件夹,添加:

    const express = require('express');
    const path = require('path');
    
    app.use(express.static(path.join(__dirname, 'build')));
    app.get('/*', function (req, res) {
        res.sendFile(path.join(__dirname, 'build', 'index.html'));
    });
    

    'build' 是在 npm run build 之后创建的 react 应用文件夹,放入你的 react 应用文件夹。

    如果没有,您必须安装 pathexpress 模块。

    并且,您应该在“get”函数中获取您的 json-server 数据库,以将其与特定的 url 一起使用:/db,就像这样:

    app.use('/db', middlewares, router);
    

    但是你应该把/db放在/*之前不要打开带有url /的数据库。

    因此,结果(server.js)将是:

    const jsonServer = require('json-server');
    const app = jsonServer.create();
    const path = require('path');
    const express = require('express');
    const middlewares = jsonServer.defaults();
    const router = jsonServer.router('db.json');
    const port = process.env.PORT || 3001;
    
    app.use('/db', middlewares, router);
    app.use(express.static(path.join(__dirname, 'build')));
    
    app.get('/*', function (req, res) {
        res.sendFile(path.join(__dirname, 'build', 'index.html'));
    });
    
    server.listen(port);
    

    【讨论】:

      【解决方案2】:

      我的 JSON 服务器上也运行 Heroku。例如,您需要将 API 路径更正为您的资源名称;

      如果您的 API 中的资源名称是“博客”;

          {
        "blogs": [
          {
            "postTitle": "My First Blog",
      

      那么你的 api 路径将是;

      https://xxxx.herokuapp.com/blogs
      

      export const baseUrl = 'https://xxxx.herokuapp.com/blogs';
      

      您不需要指定端口,但如果您这样做,则将是 Heroku 使用的端口 4000。

      【讨论】:

        猜你喜欢
        • 2021-11-21
        • 1970-01-01
        • 2019-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-05
        相关资源
        最近更新 更多