【问题标题】:Showing res.json is not a function显示 res.json 不是函数
【发布时间】:2022-02-23 18:25:00
【问题描述】:
    const Express=require('express');
    const fs=require('fs');
    const app =new Express();
    // app.get("/",(req,res)=>{
    //     res.send("Hello I am at Home");
    // })
    // app.post("/",(req,res)=>{
    //     res.send("hello i am at end point");
    // })
    const tours=JSON.parse(
        fs.readFileSync(`${__dirname}/data.json`,'utf-8')
    )
    app.get('/api',(res,req)=>{
        res.json({
            status:"success",
            data:{
                tours:tours
            }
    
        })
        console.log("server running")
    })
    app.listen(8000);

显示res.json 不是函数。

为什么会显示这个错误?我看到一个教程,其中代码运行成功,但出现错误?

【问题讨论】:

  • 你在回调函数中切换了参数的位置。第一个参数应该是请求,第二个是响应...app.get('/api' (req, res) => {...}

标签: javascript node.js express


【解决方案1】:

试试这个代码的路线

app.get('/api', (req, res) => {
    res.json({
        status:"success",
        data:{
            tours:tours
        }

    })
    console.log("server running")
})

应该是(req, res) 而不是(res, req)

【讨论】:

    【解决方案2】:

    你的回调参数被颠倒了。 应该是:

    app.get('/api', (req, res) => {
    ... 
    })
    

    【讨论】:

      【解决方案3】:

      总是你必须在你的回调中首先传递 req,因为只有在 req 之后我们才会得到响应。如下所示

      app.get('/api', (req, res) => {
      -------
      })
      

      【讨论】:

        猜你喜欢
        • 2018-03-19
        • 2018-07-05
        • 2019-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-23
        • 1970-01-01
        相关资源
        最近更新 更多