React Router 设置路由报错 "unexpected token <"

我使用react-router设置路由。在根目录下设置可以正常运行

<Router>
    <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path=":name" component={Instrument} />//这里name参数出入名字
    </Route>
</Router>

这样子可以访问localhost:3000/violonce

但是吧这个路由改一下,现在路由如下:

<Router history={createBrowserHistory()}>
    <Route pat="/" component={App}>
        <IndexRoute component={HomePage} />
        <Route path="instrument" component={Instrument}>
            <IndexRoute component={InstrumentsTest} />
            <Route path="violonce" component={InstrumentRes} />
        </Route>
        <Route path="*" onEnter= {valid} />
    </Route>
</Router>

这样子访问localhost:3000/instrument/violonce就会报错,unexpected token <.
报错位置在这儿:
图片描述图片描述

求大神指点

阅读 7.6k
2 个回答

报错信息里面有指出出错位置吧?感觉应该不是这里,

===
更新:
我今天正好碰到这个问题,你应该是自己做了某种devServer,或者用了某个配置好的devServer,js用了相对路径,导致js文件请求返回了默认的html文件。devServer需要改一下:

app.use((req, res, next) => {
  // Only fall back for GET methods which accept HTML and don't appear to
  // end with a file extension.
  if (req.method !== 'GET' || !req.accepts('html') || req.path.endsWith('.js') ||
    /\.[\w]{1,4}$/i.test(req.path)) {
    return next()
  }
  res.sendHtml('public/index.html') // 此处用你的静态html文件路径
})

上面的判断条件,根据你的情况来改。

===
更新:
原因对的,上面提的方法可能和你不一样。把你的js路径改成绝对路径就可以了,我不知道你如何配置的。

这是 语法错误 。<Route path=":name" component={Instrument} />//这里name参数出入名字。应该是你注释包的错。。注释不能这样写

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题