【问题标题】:React Uncaught SyntaxError: Unexpected token '<' and Manifest: Line: 1, column: 1, Syntax errorReact Uncaught SyntaxError: Unexpected token '<' and Manifest: Line: 1, column: 1, Syntax error
【发布时间】:2020-04-25 18:00:40
【问题描述】:

我正在从两个文件夹创建 React Web 应用程序,应用程序内的动态路由返回这些错误。静态路由工作得很好。我得到错误: 未捕获的语法错误:意外的标记“

import React, { Component } from 'react';
import './NavBar.css';
import Axios from 'axios';
import { observer } from 'mobx-react';
import UserStore from '../../src/Stores/UserStore';

class NavBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            results: {},
            apiLoading: false,
            message: ''
        };
    }

    async componentDidMount() {
        try{ //check if the user is logged in
            let res = await fetch('/isLoggedIn', { 
                method: 'post',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            });

            let result = await res.json();

            if (result && result.success) {
                UserStore.loading = false;
                UserStore.isLoggedIn = true;
                UserStore.username = result.username;                
            }else{
                UserStore.loading = false;
                UserStore.isLoggedIn = false; 
            }
        }
        catch(error){
            UserStore.loading = false;
            UserStore.isLoggedIn = false;
        }  
    }

render () {

        if(UserStore.loading) {
            return(

              <div>
                <p>Loading, please wait...</p>
              </div>

            );
        }else{            
            if(UserStore.isLoggedIn){

                let hrefString = '/account/' + UserStore.username;
                return(
                    <div className="navigation">

                        <div className="HomeButton">
                            <a href="/"><h3>Stock Track</h3></a>
                            <i id="#icon" className="fas fa-globe"></i>
                        </div>

                        <div className="NavButtons">
                            <a href={hrefString}>My Account</a>
                            <a href="/lessons">Lessons</a> 
                        </div>

                    </div>
                );

            }else{
                return(
                    <div className="navigation">

                        <div className="HomeButton">
                            <a href="/"><h3>Stock Track</h3></a>
                            <i id="#icon" className="fas fa-globe"></i>
                        </div>

                        <div className="NavButtons">
                            <a href="/register">Register</a>
                            <a href="/login">Login</a>
                            <a href="/lessons">Lessons</a>
                        </div>

                    </div>
                );
            }
        }
}

在另一个文件夹(文件夹 2)中,我有这段代码可以有效地连接两个文件夹:

app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

并且这个文件夹包含一个路由器包含:

isLoggedIn(app, db) {

        app.post('/isLoggedIn', (req,res) => {

            if(req.session.userID) {
                let cols = [req.session.userID];

                db.query('SELECT * FROM users WHERE id = ? LIMIT 1', cols, (err, 
                         data, fields) => { //add cols 
                    if(data && data.length ===1){
                        res.json({
                            success: true,
                            username: data[0].username
                        });
                        return true;
                    }else{
                        res.json({
                            success: false
                        })
                    }
                })
            }else{
                res.json({
                    success: false
                });
            } 
        });

    }

在我的 App.js(文件夹 1)中,我有一个路由器,其中包括:

<Router> 
        <Switch>

          {/* This route doesn't return the error */}

          <Route exact path="/marketoverview" component={marketOverview} /> 

          {/* But this route returns the error */}

          <Route path='/account/:username' component={MyAccount}/>

        </Switch>
</Router>

感谢您的建议

【问题讨论】:

    标签: javascript reactjs mobx mobx-react


    【解决方案1】:

    在将 repo 信息从后端 package.json 复制到前端后,我遇到了同样的问题。在 package.json 中添加“主页”行时,CRA 开发服务器似乎出错。我在控制台中收到了很多错误,其中包括 %PUBLIC_URL% 在内的一些错误从 index.html 中失败。 所以,我通过删除来解决这个问题

    homepage": "https://github.com/yourname/yourrepo",

    线。现在一切正常。也许它会对某人有用

    【讨论】:

      【解决方案2】:

      检查您在服务器中设置公共/静态路径和使用路由的顺序

      我遇到了完全相同的问题,只是在通过在浏览器中键入 URL 而不是使用链接导航到 URL 时发生了这种情况。我像这样设置了一条捕获所有路线:

      routes.js

      router.get('/*', (req, res) => {
          res.sendFile(path.resolve(__dirname, '../../client/build', 'index.html'));
      });
      

      这返回了相同的错误:

      chrome console

      Uncaught SyntaxError: Unexpected token '<'
      main.7c34eb0e.chunk.js:1 Uncaught SyntaxError: Unexpected token '<'
      manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.
      

      更改路由的顺序和公用文件夹中间件修复了它。我来自:

      server.js

      app.use('/', routes);
      app.use(express.static(path.join(__dirname, '../client/build')));
      

      到:

      app.use(express.static(path.join(__dirname, '../client/build')));
      app.use('/', routes);
      

      【讨论】:

        【解决方案3】:

        检查 public/ 文件夹中的 manifest.json 文件。如果您没有,则创建一个并添加此默认内容。

        {
          "short_name": "React App",
          "name": "Create React App Sample",
          "icons": [],
          "start_url": ".",
          "display": "standalone",
          "theme_color": "#000000",
          "background_color": "#ffffff"
        }
        
        

        在终端中停止你的服务器并再次运行npm start

        【讨论】:

          【解决方案4】:

          如果你仍然面临这个问题并且你正在使用 express,那么试试这个

          在你写的文件夹2中

          app.get('/*', function(req, res) {
              res.sendFile(path.join(__dirname, 'build', 'index.html'));
          });
          

          但是,如果您不使用它,那么它将显示您遇到的错误

          app.use(express.static(path.join(__dirname, "build")));
          

          只需使用上述内容,您就可以开始了。

          但在我的情况下,当我使用上述内容时,页面已加载,但未从 app.get('/') 加载对 / 的请求,而是通过我们刚刚在上面添加的行加载该页面,这里我想要那个从app.get('/') 加载的页面,因为我正在发送一些cookie,因此我将上面的行替换为以下内容:

          app.use('/static', express.static(path.join(__dirname, "build/static")));
          app.use('/manifest.json', express.static(path.join(__dirname, "build", "manifest.json")));
          

          您还可以包含 favicon.ico

          【讨论】:

            【解决方案5】:

            将它部署到 Firebase 后,我也遇到了同样的问题。在package.json 中添加homepage 行时,CRA 开发服务器似乎出现错误。我在控制台中收到了很多错误,其中包括%PUBLIC_URL% 在内的一些错误从 index.html 中失败。所以,我通过从package.json 中删除"homepage": "https://github.com/yourname/yourrepo" 来解决这个问题。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-02-04
              • 2016-09-19
              • 2017-11-24
              • 1970-01-01
              • 2021-05-15
              相关资源
              最近更新 更多