【问题标题】:Issue with rendering express template with node.js使用 node.js 渲染 express 模板的问题
【发布时间】:2015-10-21 09:49:00
【问题描述】:

我在运行 node.js 服务器时呈现“EJS”Express 模板时遇到问题。我提供了下面的代码。如您所见,我正在实现http.createServer(function (req, res) 来读取和写入客户端消息。但是保存 HTML 代码的模板不会被渲染。该代码的主要目的是让客户端向服务器发布消息“Hello from Client”,服务器使用“Hello from Server”响应客户端。

app.js(服务器端)

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , request = require ('request')
  , cheerio = require ('cheerio')
  , $;
 

var app = express();
//console.log($('[class = "orange"]').attr('id'));
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(function (req, res) {
var body="";
    console.log('Request received: ');
    req.on('data', function (chunk) {
        body +=chunk;        
    });
    req.on('end', function(){
    	console.log("Body: "+body);
    	res.write('Hello from Server');
    	res.end();
    });

}).listen(3000);

index.ejs(客户端)

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>

  <body>
    <h1><%= title %></h1>
      <input type="button" id="stopButton" value="Button1"/>
      <input type="button" id="stopButton2" value="Button2"/>
    <p>Welcome to <%= title %></p>
  <ul id="fruits">
  <li id= "1" class="apple">Apple</li>
  <li id = "2" class="orange">Orange</li>
  <li id = "3" class="pear">Pear</li>
</ul>
  <script type="text/javascript">
      $(document).ready(function () {
          var formData = {data: "Hello from Client"};
           $.ajax({
               url: 'http://localhost:3000',
               dataType: "json",
               type: 'POST',
               data: formData,
               jsonpCallback: 'callback', 
               success: function (data, textStatus, jqXHR) {
                var ret = jQuery.parseJSON(data);
                console.log(ret.msg);
               },
               error: function (jqXHR, textStatus, errorThrown) {
                 console.log("Error received");
               }
          });
      });
 </script> 
 </body>
</html>

包.JSON

{
  "name": "NewProject",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.2.6",
    "ejs": "*"
  }
}

之前我尝试过使用app.get,它已经奏效了。

使用app.get()request()http.createServer() 的主要区别是什么。我们什么时候应该使用什么?

【问题讨论】:

    标签: node.js http express


    【解决方案1】:

    那样做是行不通的。看看文档:

    例如:

    var express = require('express');
    var bodyParser = require('body-parser')
    var app = express();
    
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
    
    // parse application/json
    app.use(bodyParser.json())
    
    app.post('/hello', function (req, res) {
      res.send("Hello from server");
    });
    
    var server = app.listen(3000, function () {
      var host = server.address().address;
      var port = server.address().port;
    
      console.log('Example app listening at http://%s:%s', host, port);
    });
    

    另外,请使用最新版本的 Express,你的已经过时了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-28
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多