Node.js - EJS example

一个人想着一个人 提交于 2019-12-03 02:09:48

You need to send something to the response. From the connect hello-world

var connect = require('../../lib/connect');

var server = connect.createServer(function(req, res){
  var body = 'Hello World';
  res.writeHead(200, {
      'Content-Type': 'text/plain'
    , 'Content-Length': body.length
  });
  res.end(body);
});

server.listen(3000);
console.log('Connect server listening on port 3000');

So for your app you'll want to replace:

function(req,res) {
 ejs.render('hi');
}

With something like:

function(req,res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end(ejs.render('hi'));
}

Does that work?

try this: (assuming you have the express and ejs modules installed)

var express = require('express');
var app = express.createServer();
app.configure(function() {
    app.use(express.bodyParser());
    app.use(express.static('./static/'));
    app.use(app.router);
});
app.set('view engine', 'ejs');
app.set('view options', {
    layout: false
});
app.get('/', function(req, res) {
res.render('index', {
    message : 'De groeten'
});
});
app.listen(3000);

and put a view in './views'. call it 'index.ejs' and fill it with some html:

<html>
<head>
<title></title>
</head>

<body>
<p>
<%= message %>
</p>
</body>
</html>

works for me!

Set your view engine to use ejs.

app.set("view engine", "ejs");

Now set up the root route so that it will load something when you access your server from a browser, see below.

var app = express();

// ROOT ROUTE
app.get("/", function(req, res) {
  res.render("landingpage"); // use to render an ejs template page
  res.send("hello world"); // to render an empty page with the hello world message
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!