简体   繁体   English

React Uncaught SyntaxError: 意外的标记 '<' and Manifest: Line: 1, column: 1, Syntax error

[英]React Uncaught SyntaxError: Unexpected token '<' and Manifest: Line: 1, column: 1, Syntax error

I am creating React web app from two folders and the dynamic routes within the app return these errors.我正在从两个文件夹创建 React web 应用程序,应用程序中的动态路由返回这些错误。 Static routes work just fine. Static 路线工作得很好。 I get the errors: Uncaught SyntaxError: Unexpected token '<' manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.我收到错误: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:在另一个文件夹(文件夹 2)中,我有这段代码可以有效地连接两个文件夹:

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:在我的 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>

Thank you for your suggestions谢谢你的建议

I have faced the same problem after copying repo info from my backend package.json to frontend.从我的后端 package.json 复制回购信息到前端后,我遇到了同样的问题。 It seems to be an error for CRA development server when adding "homepage" line in package.json.在 package.json 中添加“主页”行时,似乎是 CRA 开发服务器出错。 I received a lot of errors in console, this one and some including %PUBLIC_URL% fails from index.html.我在控制台中收到了很多错误,其中包括 %PUBLIC_URL% 在内的一些错误从 index.html 失败。 So, I fixed this by removing所以,我通过删除来解决这个问题

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

line.线。 All works fine now.现在一切正常。 Maybe it will be useful for someone也许它对某人有用

Check the order you are setting the public/static path and using routes in your server检查您在服务器中设置公共/静态路径和使用路由的顺序

I had the exact same problem except it happened when navigating to urls by typing them in the browser instead of using links.我遇到了完全相同的问题,只是在通过在浏览器中键入 URL 而不是使用链接导航到 URL 时发生了这种情况。 I setup a catch all route like so:我设置了一条捕获所有路线,如下所示:

routes.js

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

This returned the same errors:这返回了相同的错误:

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.

Changing the order of the routes and public folder middleware fixed it.更改路由和公用文件夹中间件的顺序修复了它。 I went from:我来自:

server.js

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

to:至:

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

Check your manifest.json file in your public/ folder.检查public/文件夹中的 manifest.json 文件。 If you don't have one, then create one and add this default content.如果您没有,则创建一个并添加此默认内容。

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

Stop your server in the terminal and run npm start again.在终端中停止服务器并再次运行npm start

If you are stilling facing this issue and you are using express then try this如果你仍然面临这个问题并且你正在使用 express 然后试试这个

In your folder2 you had written在你的文件夹2中你写过

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

But are if you are not using this then it is going to show the error which you are getting但是,如果您不使用它,那么它将显示您遇到的错误

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

Just use the above and you are good to go.只需使用上述内容,您就可以使用 go。

But in my case when i use the above then the page is loaded but get request to / is not loaded from app.get('/') instead that page is loaded through the line which we just added above, and here I want that page loaded from app.get('/') as i was sending some cookies, so for that I replace above line with following:但是在我的情况下,当我使用上述内容时,页面已加载,但获取到/的请求并未从app.get('/')加载,而是通过我们刚刚在上面添加的行加载该页面,在这里我想要那个当我发送一些 cookies 时从app.get('/')加载的页面,因此我将上面的行替换为以下内容:

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

you can also include favicon.ico您还可以包括 favicon.ico

I have faced the same problem after deploying it to Firebase. It seems to be an error for the CRA development server when adding the homepage line in package.json .部署到Firebase后也遇到了同样的问题,好像是CRA开发服务器在package.json中添加homepage行时出错。 I received a lot of errors in the console, this one and some including %PUBLIC_URL% fails from index.html.我在控制台中收到了很多错误,这个错误和一些包括%PUBLIC_URL%的错误来自 index.html。 So, I fixed this by removing "homepage": "https://github.com/yourname/yourrepo" from package.json .因此,我通过从package.json中删除"homepage": "https://github.com/yourname/yourrepo"来解决这个问题。

Commenting as I have had the same issue.评论因为我有同样的问题。 The HTML file was being served because the order of the code was incorrect, as referenced in the create-react-app deploy doc Below is the correct order: Note: nothing else needed to be changed, just the server.js code正在提供 HTML 文件,因为代码的顺序不正确,正如create-react-app 部署文档中所引用的 下面是正确的顺序: 注意:不需要更改任何其他内容,只需更改 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')); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在服务器端口 5000 上运行应用程序时出错,Uncaught SyntaxError: Unexpected token '<' and Manifest: Line: 1, column: 1, Syntax error - Errors when running app on server port 5000, Uncaught SyntaxError: Unexpected token '<' and Manifest: Line: 1, column: 1, Syntax error Javascript 反应 Uncaught SyntaxError: Unexpected token &#39;&lt;&#39; 或 Syntax error - Javascript react Uncaught SyntaxError: Unexpected token '<' or Syntax error Json语法错误:语法未正确:错误的令牌[ - Json syntax error:Uncaught SyntaxError: Unexpected token [ 第5行出现未捕获到的SyntaxError:意外令牌) - Uncaught SyntaxError: Unexpected token ) on line 5 Uncaught SyntaxError: Unexpected token '&lt;' React - Uncaught SyntaxError: Unexpected token '<' React Uncaught SyntaxError: Unexpected token &lt; with React - Uncaught SyntaxError: Unexpected token < with React 未捕获的 SyntaxError:意外的标记 '&lt;' (React) - Uncaught SyntaxError: Unexpected token '<' (React) 未捕获的SyntaxError:React中的意外令牌&lt; - Uncaught SyntaxError: Unexpected token < in React 未捕获的语法错误:意外令牌&lt;第1行 - Uncaught Syntax Error: Unexpected token < on line 1 错误:未捕获的SyntaxError:意外的令牌& - Error: Uncaught SyntaxError: Unexpected token &
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM