簡體   English   中英

SyntaxError:JSON.parse:JSON數據的第1行第1列出現意外字符嗎?

[英]SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data?

誰能告訴我為什么從硬盤驅動器訪問數據時,此代碼為什么能在HTML頁面中完美地工作,但是當我將其添加到express和node中時,會得到一個

SyntaxError:JSON.parse:JSON數據的第1行第1列出現意外字符

具有完美格式的代碼。 我知道我使用格式化程序對其進行了測試,甚至手動創建了一個json對象。 這是代碼:

<html>
    <!doctype html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="description" content="">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Untitled</title>
        </head>
        <body>

    <div id="output"></div>

          <button id="getProperty">Get Property</button>

          <script>
            document.getElementById('getProperty').addEventListener('click', getProperty);


            function getProperty() {
                fetch('2016-regular.json')
                .then((res) => res.json())
                .then((data) => {
                    let output = '<h2>Property</h2>';
                    console.log(data);
                    data.propertystandings.propertystandingsentry.forEach(function(propertyEntry){
                        output += `
                            <ul>
                                <li>id: ${propertyEntry.property.ID}</li>
                                <li>city: ${propertyEntry.property.City}</li>
                                <li>prop name: ${propertyEntry.property.Name}</li>
                                <li>prop name: ${propertyEntry.rank}</li>
                            </ul>
                        `;
                    });
                document.getElementById('output').innerHTML = output;
                })
            }
          </script>

        </body>
    </html>
</html>
</html>
But then this code in express causes the error- same exact file that worked perfectly before ran thru express now causes this error: 
**"index.ejs"**

    <div id="output"></div>

          <button id="getProperty">Get Property</button>

    <script>

            document.getElementById('getProperty').addEventListener('click', getProperty);


            function getProperty() {
                /*fetch('sample.txt')
                .then(function(res) {
                    return res.text();
                })
                .then(function(data){
                    console.log(data);
                });*/
                fetch("2016-regular.json")
                .then((res) => res.json())
                .then((data) => {
                    console.log(data);//**won't even read the data without that error**
                });
            }
    </script>


**express code**
var express = require('express');
//var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');

var app = express();

app.use(bodyParser());
app.use(cors());

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/', function (request, response) {
    response.render('index.ejs');
});

app.listen(8000, function() {
    console.log('running on 8000');
});

任何想法,為什么在訪問文件夾時這在純HTML中都能正常工作,或者如果我手動在硬盤上創建並保存文件,但是一旦我將其放入Express或嘗試訪問API,數據就來自(最終目標)錯誤SyntaxError:JSON.parse:JSON數據第1行第1列的意外字符

我認為最重要的是,您需要確保JSON文件可訪問/可加載,然后確保它是有效的。 這是一個最小的工作示例。 您的app.js應該很簡單:

var express = require('express');
var index = require('./routes/index');
var app = express();

app.set('views', 'views');
app.set('view engine', 'ejs');

app.use(express.static('public'));

app.use('/', index);

module.exports = app;

您的route / index.js很簡單:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

您的views / index.ejs應該是:

<html>
<body>
  <div id="output">JSON contents will appear here.</div>  
  <button id="getProperty">Click to load JSON</button>

  <script>
      document.getElementById('getProperty').addEventListener('click', getProperty);  
      function getProperty() {
          fetch("./2016-regular.json")
          .then((res) => res.json())
          .then((data) => {
              document.getElementById('output').innerHTML = JSON.stringify(data);
          });
      }
  </script>
</body>
</html>     

最后,確保將JSON文件保存在./public/2016-regular.json。 這是我的:

{“ item1”:“ value1”,“ item2”:“ value2”,“ item3”:“ value3”}

測試1將瀏覽器指向http:// localhost:3000 / 2016-regular.json,請確保您的JSON文件可訪問(請注意,如果您在其他端口上運行,則可能必須更改端口)。

測試2導航到http:// localhost:3000 / ,然后單擊按鈕。 文件內容應出現在結果div中。

完整的工作代碼 在這里 只需克隆存儲庫,然后

cd exp1
npm install
npm start

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM