Express/Node.js错误:参考错误:未定义Res [英] Express/Node.js error: Reference Error: Res is not defined

查看:37
本文介绍了Express/Node.js错误:参考错误:未定义Res的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在尝试为小组的应用程序创建一个基本的CRUD应用程序,但是我在使用基本行时遇到了一些麻烦.为了构建我的原始应用程序,我目前正在使用node.js,express和mongodb.我的部分代码遇到了麻烦,我想知道您是否可以向正确的方向指出.

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. To build my crud application, I'm currently using node.js, express, and 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" 

我的问题:每次我初始化res.render(视图,本地)时,我的节点服务器崩溃.这是我得到的错误.

my problem: every time i initialize res.render(view, locals) my node server crashes. 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

我的代码:到目前为止,这就是我对server.js的了解.现在,每当我尝试导入index.ejs文件以及每当尝试导入以下行时,我都会收到错误消息:

my code: this is what i have for server.js so far. 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:

res.render(views, locals)

这是我的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
        })
    })

我们将非常感谢大家提供的任何帮助我进行故障排除的帮助.在过去的几个小时中,我一直坚持这一点.我以为res已经由express定义了?为什么要告诉我再次定义res?

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? Why am I being told to define res again?

=============================================================================

=============================================================================

现在我遇到以下错误:错误:发送标头后无法设置标头.这就是我现在拥有的:

Now i'm getting the following error: Error: Can't set headers after they are sent. this is what i have now:

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


最近感谢其他人的意见和建议,我意识到我需要更改位置并实际上明确定义res.render.


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.

我现在遇到以下调试错误:

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
    })
})

我要去哪里错了?

========================================================================我能够过去一个调试错误,并进入下一个.我完全删除了res.render并通过重新排列一些代码解决了标题问题.这是我最近的:

======================================================================= EDIT 2: i was able to get past one debugging error and onto the next. i removed res.render entirely and fixed my header issue by rearranging some of my code. 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"

推荐答案

  1. 您可以在根级别调用app.render,而只能在路由/中间件内部调用res.render.
  2. app.render 始终在回调函数中返回html,而 res.render 仅在将回调函数指定为第三个参数时才返回html.如果您在没有第三个参数/回调函数的情况下调用 res.render ,则呈现的html将以状态码200发送给客户端.
  1. You can call app.render on root level and res.render only inside a route/middleware.
  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. 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.

看看下面的例子.

app.render

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

res.render (没有第三个参数)

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

具有第三个参数的

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 内部使用 app.render 呈现模板文件.
  2. 无法设置标题意味着您无法进入正文.
  3. res.render()函数编译您的模板(请不要使用ejs),在其中插入本地语言,并从这两件事中创建html输出.
  1. res.render uses app.render internally to render template files.
  2. can't set headers means that you can't get into the body.
  3. res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.

//在这里,您设置所有模板都位于/views 目录

// here you set that all templates are located in /views directory

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});

因此,模板路径为 views/(第一部分)+ local (第二部分)+ .ejs (第三部分)=== views/local.ejs

So, the template path is views/ (first part) + local (second part) + .ejs (third part) === views/local.ejs

这篇关于Express/Node.js错误:参考错误:未定义Res的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆