Express / Node.js错误:参考错误:Res未定义
我正在尝试为我的团队应用程序创build一个基本的CRUD应用程序,但是我遇到了一些基本问题。 为了构build我的crud应用程序,我正在使用node.js,express和mongodb。 我在使用部分代码时遇到了一些麻烦,我想知道是否可以指引我朝着正确的方向发展。
(这是一个冗长的问题,我尽我所能来格式化,以免它在阅读的时候灼伤你的眼睛…对不起,如果很难读)
上下文:供参考我使用这个:
https://zellwk.com/blog/crud-express-mongodb/, currently on "Showing quotes to users"
我的问题:每次我初始化res.render(视图,本地人)我的节点服务器崩溃。 这是我得到的错误。
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文件,每当我尝试导入下面的行时,我得到一个错误:
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?
================================================== ===========================编辑:
现在我收到以下错误: Error: Can't set headers
发送后Error: Can't set headers
。 这是我现在所拥有的:
//getting this to render? app.get('views/', (req, res, views, local) =>{ res.render(views,local) })
最近的编辑:感谢来自他人的input和build议,我意识到我需要改变位置,实际上明确地定义res.render。
我现在卡在以下debugging错误:
Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
我已经改变了我的代码如下:
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 }) })
我哪里错了?
================================================== =====================编辑2:我能够通过一个debugging错误,并进入下一个。 我完全删除res.render并通过重新安排我的一些代码来解决我的头问题。 这是我最近的:
/* -------- 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 }) })
现在我正在解决以下问题:
Error: Failed to lookup view "views/index.ejs" in views direct ory "C:\Users\hcqph\gitprojects\crudbeta\views"
- 你可以在根级调用app.render,在路由/中间件内调用res.render。
-
app.render
总是返回callback函数中的html,而res.render
只有当你指定callback函数作为第三个参数res.render
这样做。 如果在不使用第三个参数/callback函数的情况下调用res.render
将呈现的html发送到状态码为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'); }) })
-
res.render
app.render
内部使用app.render
来渲染模板文件。 -
can't set headers
意味着你不能进入正文。 -
res.render()
函数编译你的模板(请不要使用ejs),在那里插入locals,然后用这两个东西创buildhtml输出。
//在这里你设置所有模板都位于/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});
所以,模板path是views/
(第一部分)+ local
(第二部分)+ .ejs
(第三部分)=== views/local.ejs
它不工作,因为在代码中没有定义res
。 如果你在你的app.get('/')
方法下看几行,那么res
就在那个function块中定义。 您需要创build另一个端点(或使用现有的app.get端点) – 例如,
app.get('/someendpoint', function(req, res) { // use res here // also must have views and local defined res.render(views, local); });
在声明服务器端点时,express会将请求和响应对象传递给你的callback函数。
- Node.js – Express.js JWT在浏览器响应中总是返回一个无效的令牌错误
- Node.js连接到一个mongodb
- 将jQuery ajax调用转换为vanilla Javascript – 不能POST / public / error
- 用json发送html文件并让浏览器重新加载该json而不用重新加载页面
- 在使用express-socket.io-session时,不推荐使用express-session选项,为什么会出现这种情况?
- Node.js JSON.stringify()导致“ 在输出。 无法用Jqueryparsing
- 在Node express应用程序中安装Entrust SSL证书
- Express和Nodejs:调用外部API的最佳方式
- node.js – 尝试使用Parse Server查询时,Heroku服务器超时?