javascript - create-react-app with node express 获取 %PUBLIC_URL%

标签 javascript node.js reactjs react-router create-react-app

我正在尝试使用快速服务器创建 react 应用程序。在我点击请求时设置服务器后,我得到了

GET http://localhost:3333/%PUBLIC_URL%/favicon.ico 400(错误请求)

错误预览它给我

URIError: Failed to decode param '/%PUBLIC_URL%/favicon.ico'
    at decodeURIComponent (<anonymous>)
    at decode_param (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/layer.js:172:12)
    at Layer.match (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/layer.js:123:27)
    at matchLayer (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:574:18)
    at next (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:220:15)
    at jsonParser (/home/owaishanif/code/flashcard-app/node_modules/body-parser/lib/types/json.js:103:7)
    at Layer.handle [as handle_request] (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:317:13)
    at /home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:335:12)

这是服务器代码

var express = require('express');
var bodyParser = require('body-parser');
var path = require ('path');

var data = {};

express()
    .use(express.static(path.resolve(__dirname, '..', 'public')))
    .use(bodyParser.json())

    .get('/api/data', (req, res) => res.json(data))

    .post('/api/data', (req, res) => res.json(data = req.body))

    .get('*', (req, res) => res.sendFile( path.resolve( __dirname, '..', 'public/index.html')))

    .listen(3333, function(){
        console.log('server running at 3333');
    });

我想使用 create react app with server.网上有文章,但是已经过时了。欢迎提供帮助提示和技巧。

最佳答案

我已经使用 create-react-app build 解决了这个问题,它创建了一个构建文件夹。 %public_url% 字符串也被幕后的一些 yarn 脚本替换了。所以我们不能直接为那个文件夹提供服务。相反,我们必须使用 build 生成。

使用 yarn buildnpm run build。这将生成一个构建文件夹,其中包含 assetmanifest 和其他文件。

之后,使用该构建文件夹静态提供您的文件以供生产使用。

关于javascript - create-react-app with node express 获取 %PUBLIC_URL%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44862706/

相关文章:

javascript - 如何从一个 NPM 包中导出多个 ES6 模块

javascript - 如何使用 socket.io 发送消息

javascript - 如何在 JavaScript 中检查变量是否为 null 和/或未定义

javascript - 如何以及是否在 stripe 新库 @stripe/react-stripe-js 中使用服务器端

javascript - NodeJS API 函数的范围 - Firebase 函数和 Twitter API

c# - 从 Request.Files 中删除文件

javascript - 如何在 Node js和 Mongoose 中保存用户之前对密码进行哈希处理

css - 正确定位绝对定位元素的工具提示

javascript - 在 React 中切换添加到收藏夹的按钮颜色

reactjs - 有可能在 react 中捕获全局错误