我是 Web 开发领域的新手,我遇到了一个看起来很愚蠢的问题,但这花了我很多时间。
我已经制作了一个在前端运行 React 的快速服务器。我通过使用 webpack 和 bundle 解析我的 react 应用程序来运行(react 和 express 服务器),然后使用公共目录加载带有 express static 的输出文件。
这就是我可以在根路径('/')处呈现 html 文档的方式。当我尝试将 react-router 与 express 路由器一起使用时,问题就开始了。我一直在寻求解决这个问题,我发现我只需要设置一个看起来像这样的快速路线:
/*This is my actual code in the project*/
router.get('/*', (req, res, next) =>{
res.sendFile(require('../public/index.html'))
})
这段代码将运行 react,因为我是从 html 中的 script 标签调用它,React 将处理 url 并呈现它自己的组件。
但是当我尝试访问浏览器上的任何路径时,我得到了最简单的错误,SynthaxError:
C:\Users\Matthew\Desktop\Proyectos\Apid0\src\public\index.html:1
<!DOCTYPE html>
^
SyntaxError: Unexpected token '<'
at wrapSafe (internal/modules/cjs/loader.js:1067:16)
at Module._compile (internal/modules/cjs/loader.js:1115:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Module.require (internal/modules/cjs/loader.js:1040:19)
at require (internal/modules/cjs/helpers.js:72:18)
at C:\Users\Matthew\Desktop\Proyectos\Apid0\src\routes\index.js:5:18
at Layer.handle [as handle_request]
(C:\Users\Matthew\Desktop\Proyectos\Apid0\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Matthew\Desktop\Proyectos\Apid0\node_modules\express\lib\router\route.js:137:13)
有人可以帮我解决这个问题吗?