javascript React未捕获语法错误:意外的标记“〈”和清单:行:1,列:1,语法错误

ghhkc1vu  于 2022-12-02  发布在  Java
关注(0)|答案(6)|浏览(233)

I am creating React web app from two folders and the dynamic routes within the app return these errors. Static routes work just fine. I get the errors: Uncaught SyntaxError: Unexpected token '<' manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.

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>
                );
            }
        }
}

In the other folder (folder 2) I have this code that effectively joins both folders:

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

And this folder contains a router contains:

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
                });
            } 
        });

    }

In my App.js (folder 1) I have a router that includes:

<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>

Thank you for your suggestions

yv5phkfx

yv5phkfx1#

在从我的后端package.json复制repo信息到前端后,我遇到了同样的问题。在package.json中添加“主页”行时,CRA开发服务器似乎出现了错误。我在控制台中收到了很多错误,这一个和一些错误包括%PUBLIC_URL%从index.html失败。因此,我通过删除
homepage": "https://github.com/yourname/yourrepo",
行。现在一切正常。也许对某人有用

dgjrabp2

dgjrabp22#

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

我遇到了完全相同的问题,除了在浏览器中键入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);
vdgimpew

vdgimpew3#

检查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

ctehm74n

ctehm74n4#

如果您仍面临此问题,并且正在使用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

7kqas0il

7kqas0il5#

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

6qfn3psc

6qfn3psc6#

评论,因为我有同样的问题。HTML文件被送达,因为代码的顺序是不正确的,如在create-react-app deploy doc中引用以下是正确的顺序:注意:不需要更改任何其他内容,只需要更改server.js代码

// Have Node serve the files for our built React app
app.use(express.static(path.join(__dirname, '../client/build')));

/// All other GET requests not handled before will return our React app
app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, '../client/build', 'index.html'));
});

相关问题