簡體   English   中英

無法解析 JSON 文件

[英]Can't parse a JSON file

我開始學習 node.js 並且遇到了錯誤。 這是代碼:

const server = http.createServer((req, res) =>{ //request, response
    const pathName = req.url;

    if (pathName === '/' || pathName === '/overview'){
        res.end('This is the OVERVIEW') //  res trimite catre client, req trimite catre server
    } else if (pathName === '/product'){
        res.end('This is the PRODUCT');
    } else if (pathName === '/api') {

        fs.readFile(`${__dirname}/dev-data/data.json`, 'utf-8', (err, data) => {
            const productData = JSON.parse(data);
            response.writeHead(200, { 'Content-type': 'application/json' });
            response.end(data);
        });

    } else{
        res.writeHead(404, {
            'Content-type': 'text/html', 
            'my-own-header': 'hello-world'
        });
        res.end('<h1>This page could not be found!</h1>');
    }

    res.end('Hello from the server!');
});

問題在於:

else if (pathName === '/api') {

        fs.readFile(`${__dirname}/dev-data/data.json`, 'utf-8', (err, data) => {
            const productData = JSON.parse(data);
            response.writeHead(200, { 'Content-type': 'application/json' });
            response.end(data);
        });

我得到的錯誤:

未定義:1 未定義 ^

SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at ReadFileContext.callback (c:\Users\40721\Desktop\nodeJs&Express\complete-node-bootcamp-master\1-node-farm\index.js: 49:38) 在 FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:257:13)

我要讀取的 data.json 文件是這樣的:

[
  {
    "id": 0,
    "productName": "Fresh Avocados",
    "image": "🥑",
    "from": "Spain",
    "nutrients": "Vitamin B, Vitamin K",
    "quantity": "4 🥑",
    "price": "6.50",
    "organic": true,
    "description": "A ripe avocado yields to gentle pressure when held in the palm of the hand and squeezed. The fruit is not sweet, but distinctly and subtly flavored, with smooth texture. The avocado is popular in vegetarian cuisine as a substitute for meats in sandwiches and salads because of its high fat content. Generally, avocado is served raw, though some cultivars, including the common 'Hass', can be cooked for a short time without becoming bitter. It is used as the base for the Mexican dip known as guacamole, as well as a spread on corn tortillas or toast, served with spices."
  },
  {
    "id": 1,
    "productName": "Goat and Sheep Cheese",
    "image": "🧀",
    "from": "Portugal",
    "nutrients": "Vitamin A, Calcium",
    "quantity": "250g",
    "price": "5.00",
    "organic": false,
    "description": "Creamy and distinct in flavor, goat cheese is a dairy product enjoyed around the world. Goat cheese comes in a wide variety of flavors and textures, from soft and spreadable fresh cheese to salty, crumbly aged cheese. Although it’s made using the same coagulation and separation process as cheese made from cow’s milk, goat cheese differs in nutrient content."
  },
  {
    "id": 2,
    "productName": "Apollo Broccoli",
    "image": "🥦",
    "from": "Portugal",
    "nutrients": "Vitamin C, Vitamin K",
    "quantity": "3 🥦",
    "price": "5.50",
    "organic": true,
    "description": "Broccoli is known to be a hearty and tasty vegetable which is rich in dozens of nutrients. It is said to pack the most nutritional punch of any vegetable. When we think about green vegetables to include in our diet, broccoli is one of the foremost veggies to come to our mind. Broccoli is a cruciferous vegetable and part of the cabbage family, which includes vegetables such as Brussel sprouts and kale. Although the tastes are different, broccoli and these other vegetables are from the same family."
  },
  {
    "id": 3,
    "productName": "Baby Carrots",
    "image": "🥕",
    "from": "France",
    "nutrients": "Vitamin A, Vitamin K",
    "quantity": "20 🥕",
    "price": "3.00",
    "organic": true,
    "description": "The carrot is a root vegetable that is often claimed to be the perfect health food. It is crunchy, tasty and highly nutritious. Carrots are a particularly good source of beta-carotene, fiber, vitamin K, potassium and antioxidants. Carrots have a number of health benefits. They are a weight loss friendly food and have been linked to lower cholesterol levels and improved eye health."
  },
  {
    "id": 4,
    "productName": "Sweet Corncobs",
    "image": "🌽",
    "from": "Germany",
    "nutrients": "Vitamin C, Magnesium",
    "quantity": "2 🌽",
    "price": "2.00",
    "organic": false,
    "description": "Also known as maize, corn is one of the most popular cereal grains in the world. Popcorn and sweet corn are commonly eaten varieties, but refined corn products are also widely consumed, frequently as ingredients in foods. These include tortillas, tortilla chips, polenta, cornmeal, corn flour, corn syrup, and corn oil. Whole-grain corn is as healthy as any cereal grain, rich in fiber and many vitamins, minerals, and antioxidants."
  }
]

您是否將圖像屬性存儲為圖像的位置? JSON 僅接受以下數據類型:

 a string
    a number
    an object (JSON object)
    an array
    a boolean
    null

暫無
暫無

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

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