简体   繁体   English

Express / Node.js错误:参考错误:未定义Res

[英]Express/Node.js error: Reference Error: Res is not defined

I'm trying to create a basic CRUD application right now for my group's application but I'm having some trouble with a basic line. 我现在正在尝试为小组的应用程序创建一个基本的CRUD应用程序,但是我在使用基本行时遇到了一些麻烦。 To build my crud application, I'm currently using node.js, express, and mongodb. 为了构建我的原始应用程序,我目前正在使用node.js,express和mongodb。 I'm having some trouble with part of my code and I was wondering if you could point me toward the right direction. 我在部分代码上遇到了麻烦,我想知道是否可以为我指明正确的方向。

(this is a lengthy question. i tried my best to format this so that it wouldn't burn your eyes while reading... sorry if it is hard to read) (这是一个冗长的问题。我尽力将其格式化,以使它在阅读时不会灼伤您的眼睛……如果很难阅读,对不起)

context: for reference I'm using this: 上下文:供参考,我正在使用此:

https://zellwk.com/blog/crud-express-mongodb/, currently on "Showing quotes to users" 

my problem: every time i initialize res.render(view, locals) my node server crashes. 我的问题:每次我初始化res.render(view,locals)时,我的节点服务器崩溃。 here's the error that i'm getting. 这是我得到的错误。

res.render(view, locals)
    ReferenceError: res is not defined
        at Object.<anonymous> (C:\Users\hcqph\xx\xcxx\server.js:35:1)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
        at Module.runMain (module.js:604:10)
        at run (bootstrap_node.js:393:7)
        at startup (bootstrap_node.js:150:9)
        at bootstrap_node.js:508:3

my code: this is what i have for server.js so far. 我的代码:到目前为止,这是我对server.js的了解。 right now, i'm getting an error whenever i try to import my index.ejs file and whenever i try to import the following lines: 现在,每当我尝试导入index.ejs文件以及每当尝试导入以下行时,我都会收到错误消息:

res.render(views, locals)

this is my code for server.js 这是我的server.js代码

    const express = require('express');
    const bodyParser = require('body-parser')
    const app = express();
    const MongoClient = require('mongodb').MongoClient

  var db

    MongoClient.connect('mongodb://omittedforprivacy', (err, database) => {
        if (err) return console.log(err)
        db = database

        app.listen(3000, () => {
            console.log('connected to mongoDB successfully. now listening on port 3000 ')
        })

    })

    /* -------- for team documentation --------
    BODYPARSER makes it possible to handle reading data from form element in index.html.  URLENCODED method within body-parser tells body-parser to extract data from form element and add them to the body element property in request object.
    ------------------------------------------------ */ 
    app.use(bodyParser.urlencoded({extended: true}))

    //set 'ejs' template engine, and default extension is ejs
    app.set('view engine', 'ejs')

    //CAN'T FIGURE OUT WHY THIS ISN'T WORKING
    res.render(views, locals)

    /* -------- for team documentation --------
    => = replacement for function

    app.get hand a GET request (read operation)
    ------------------------------------------------ */
    app.get('/', (req, res) => {
        //serves index.html back to browser
        res.sendFile(__dirname + '/index.html')

        //gets list of trips from mlab.com
        var cursor = db.collection('trips').find()

        //retrieves list of trips retrieved from mlab
        db.collection('trips').find().toArray(function(err, results) {
            if(err) return console.log(err)

            //renders index.ejs
            res.render('index.ejs', {trips:results})
        })
    })



    /* app.post handles a create request */
    app.post('/trips', (req, res) => {
        db.collection('trips').save(req.body, (err, result) =>{
            if (err) return console.log(err)

            console.log('saved to database')
            res.redirect('/') //causes browser to reload
        })
    })

Any assistance that you all could provide to help me troubleshoot would be really really appreciated. 大家都可以提供任何帮助我进行故障排除的帮助,我们将非常感谢。 I've been stuck on this for the past few hours. 在过去的几个小时里,我一直坚持这一点。 I thought res was already defined by express? 我以为res已经由express定义了? Why am I being told to define res again? 为什么要告诉我再次定义res?

============================================================================= EDIT: ================================================== ==========================编辑:

Now i'm getting the following error: Error: Can't set headers after they are sent. 现在,我收到以下错误: Error: Can't set headers发送Error: Can't set headersError: Can't set headers this is what i have now: 这就是我现在所拥有的:

//getting this to render? 
app.get('views/', (req, res, views, local) =>{ res.render(views,local) })

most recent edit: Thanks to input and suggestions from others, I realized that I needed to change the location and actually explicitly define res.render. 最新编辑:感谢其他人的意见和建议,我意识到我需要更改位置并明确定义res.render。

I'm now stuck on the following debugging error: 我现在遇到以下调试错误:

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)

I have changed my code as follows: 我将代码更改如下:

app.get('/', (req, res) => {
    //serves index.html back to browser
    res.sendFile(__dirname + '/index.html')

    //gets list of trips from mlab.com
    var cursor = db.collection('trips').find()

    //retrieves list of trips retrieved from mlab
    db.collection('trips').find().toArray(function(err, results) {
        if(err) return console.log(err)

        //renders index.ejs
        res.render('index.ejs', {trips:results})
    })
})

//set 'ejs' template engine, and default extension is ejs
app.set('view engine', 'ejs')

//getting this to render? 
app.get('views/', (req, res) =>{
    res.render(views,local)
})


/* app.post handles a create request */
app.post('/trips', (req, res) => {
    db.collection('trips').save(req.body, (err, result) =>{
        if (err) return console.log(err)

        console.log('saved to database')
        res.redirect('/') //causes browser to reload
    })
})

where am i going wrong? 我要去哪里错了?

======================================================================= EDIT 2: i was able to get past one debugging error and onto the next. ================================================== =====================编辑2:我能够克服一个调试错误,然后转到下一个调试错误。 i removed res.render entirely and fixed my header issue by rearranging some of my code. 我完全删除了res.render并通过重新排列一些代码解决了标题问题。 this is my most recent: 这是我最近的:

/* -------- for team documentation --------
BODYPARSER makes it possible to handle reading data from form element in index.html.  URLENCODED method within body-parser tells body-parser to extract data from form element and add them to the body element property in request object.
------------------------------------------------ */ 
app.use(bodyParser.urlencoded({extended: true}))

//set 'ejs' template engine, and default extension is ejs
app.set('view engine', 'ejs')

/* -------- for team documentation --------
=> = replacement for function

app.get hand a GET request (read operation)
------------------------------------------------ */
app.get('/', (req, res) => {
    //serves index.html back to browser
    res.sendFile(__dirname + '/index.html')

    //gets list of trips from mlab.com
    var cursor = db.collection('trips').find()

    //retrieves list of trips retrieved from mlab
    db.collection('trips').find().toArray(function(err, results) {
        if(err) return console.log(err)

        //renders index.ejs
        res.render('views/index.ejs', {trips:results})
    })
})



/* app.post handles a create request */
app.post('/trips', (req, res) => {
    db.collection('trips').save(req.body, (err, result) =>{
        if (err) return console.log(err)

        console.log('saved to database')
        res.redirect('/') //causes browser to reload
    })
})

now i am working on fixing the following problem: 现在我正在解决以下问题:

Error: Failed to lookup view "views/index.ejs" in views direct                      ory "C:\Users\hcqph\gitprojects\crudbeta\views"

Its not working because res is not defined at that point in the code. 它不起作用,因为在该点上未定义res If you look a few lines lower at your app.get('/') method, res is defined in that function block. 如果您在app.get('/')方法的下方看几行,则res在该功能块中定义。 You would need to create another endpoint (or use your existing app.get endpoint) - for example, 您将需要创建另一个端点(或使用现有的app.get端点)-例如,

app.get('/someendpoint', function(req, res) {
    // use res here
    // also must have views and local defined
    res.render(views, local);
});

express will pass in the request and response object to your callback function when declaring a server endpoint. 在声明服务器端点时,express会将请求和响应对象传递给您的回调函数。

  1. You can call app.render on root level and res.render only inside a route/middleware. 您可以在根级别调用app.render,而只能在路由/中间件内部调用res.render。
  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. app.render始终在回调函数中返回html,而res.render仅在将回调函数指定为第三个参数app.render返回。 If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200. 如果您res.render没有第三个参数/回调函数的情况下调用res.render ,则呈现的html将以状态代码200发送给客户端。

Take a look at the following examples. 看下面的例子。

app.render

app.render('index', {title: 'res vs app render'}, function(err, html) {
    console.log(html)
});

res.render without third parameter 没有第三个参数的res.render

app.get('/render', function(req, res) {
    res.render('index', {title: 'res vs app render'})
})

res.render with third parameter 具有第三个参数的res.render

app.get('/render', function(req, res) {
    res.render('index', {title: 'res vs app render'}, function(err, html) {
        console.log(html);
        res.send('done');
    })
})
  1. res.render uses app.render internally to render template files. res.render app.render内部使用app.render渲染模板文件。
  2. can't set headers means that you can't get into the body. can't set headers意味着您无法进入正文。
  3. res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things. res.render()函数编译您的模板(请不要使用ejs),在其中插入本地语言,并从这两件事中创建html输出。

// here you set that all templates are located in /views directory //在这里设置所有模板都位于/views目录中

app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `local` template
response.render("local", {local: local_json});

So, the template path is views/ (first part) + local (second part) + .ejs (third part) === views/local.ejs 因此,模板路径为views/ (第一部分)+ local (第二部分)+ .ejs (第三部分)=== views/local.ejs

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM