【问题标题】:Express problem: "," is expected, but when it's added, the error still shows快递问题:“,”是预期的,但添加时仍然显示错误
【发布时间】:2021-01-15 00:29:57
【问题描述】:

我对编码还是很陌生,目前正在探索 Express。我遇到了这个问题“,”虽然我尝试按照说明添加它,但它仍然显示:(

const express = require("express"); const fs = require("fs")
 
const app = express();
 
const PORT = 3000;

app.get('/products', (req, res) => {
     fs.readFile('./masterdata/products.json', (err, data) => {
         if(err){
             res.status(400).json({
                 message: "Something wrong when loading the data"
             })
             res.status(200).json(JSON.parse(data))
             // res.json([
             //     "Apple",
             //     "redmi",
             //     "One plus"
             // ])
 
         }
     } }),
 
 app.get('/orders', (req, res) => {
     res.json([
         {
             id: 1, 
             paid: false, 
             user_id: 1
         },
         {
             id: 2, 
             paid: true, 
             user_id: 2
         }
     ]) 
 })
 
 app.listen(PORT, () => {
 console.log(`Server Listening on port ${PORT}`); })

我收到的错误消息是 (',' expected.)

请帮我弄清楚。很感谢任何形式的帮助。非常感谢!

【问题讨论】:

  • 请正确格式化代码(使用代码格式,而不是引号格式)并告诉哪一行抛出错误。

标签: node.js json express


【解决方案1】:

我格式化了你的代码并得到了这个:

app.get('/products', (req, res) => { 
    fs.readFile('./masterdata/products.json', (err, data) => { 
        if(err){ 
            res.status(400).json({ message: "Something wrong when loading the data" }) 
            res.status(200).json(JSON.parse(data))
        }  
    }
})

这样,我收到了与您相同的错误。但是您缺少)

app.get('/products', (req, res) => { 
    fs.readFile('./masterdata/products.json', (err, data) => { 
        if(err){
            res.status(400).json({ message: "Something wrong when loading the data" }) 
            res.status(200).json(JSON.parse(data))
        }
    }) // Added paren to close readFile
})

注意,您可能希望您的 res.status(200)if 块之外

app.get('/products', (req, res) => { 
fs.readFile('./masterdata/products.json', (err, data) => { 
    if(err){
        res.status(400).json({ message: "Something wrong when loading the data" })
    } else {
        res.status(200).json(JSON.parse(data))
    }
  })
})

【讨论】:

    猜你喜欢
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2016-03-04
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    相关资源
    最近更新 更多