这是我第一次在Node.js应用中使用路由器。通常,我只会写一个HTML页面,但在这里我使用的是Jade模板。我的问题是页面呈现为在Jade中编写,没有对我在您在此处看到的index.js脚本中编写的画布所做的任何更改。是否有一个特殊的功能来重新呈现具有这些更改的页面?
index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
var canvas = document.getElementById("myCanvas");
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
var context = canvas.getContext("2d");
context.fillStyle = "#FF0000";
context.fillRect(0,0,150,75);
});
module.exports = router;
index.jade:
extends layout
block content
h1= title
p Welcome to #{title}
canvas#myCanvas(width='200', height='100', style='border:1px solid #000000;')
app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
答案 0 :(得分:1)
您无法在服务器端访问document
对象。因此,我可以看到您已经在app.js文件中调用了bodyParser
中间件,所以现在您需要做的就是在jade文件canvas(name="myCanvas")
中为画布命名
来自index.js
的{{1}}访问画布:
req.body