nodejs + express + ejs + mongodb 一个非常简单的前后端开发的实例2

本文指导您使用Node.js创建一个基本的应用程序,并通过Sublime Text编辑器进行操作。包括设置环境、配置Express、添加路由、运行服务器等步骤,最终实现显示Hello, World!的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Part2 :  LET'S DO "HELLO, WORLD!"

   Fire up your favorite text editor or IDE. I like Sublime Text a lot. Point it at your nodetest1 directory and open app.js. This is kind of the heart of your, well, app. Not a big surprise there. Here's a breakdown of what you're going to see:

  选择你最喜欢的编辑器或集成开发环境. 我比较喜欢 Sublime Text. 点击你的nodetest1目录下, 打开app.js文件. 这是你的应用的"心脏". 

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
1 第一部分换行前的内部如上,   This creates a bunch of basic JavaScript variables and ties them to certain packages, dependencies, node functionality, and routes. 这里创建了一连串的JS变量, 连接一些特定的包, 依赖, node和路由. 

var app = express();

2 This one's important. It instantiates Express and assigns our app variable to it. The next section uses this variable to configure a bunch of Express stuff. 这个非常重要, 实例化一个Express对象,并赋值给变量app. 后面的部分可以应用该变量配置一些Express内容. 

app.get('/', routes.index);
app.get('/users', user.list);
3 路由部分 

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
4 这部分创建了我们的http服务并launch它.

 A: 第1步: APP.JS的app.get()路由中加入

app.get('/helloworld', routes.helloworld);

 B: 第2步: 打开routes/INDEX.JS , 在文件的最后加入如下代码:

exports.helloworld = function(req, res){
  res.render('helloworld', { title: 'Hello, World!' });
};
C: 第3步: Views下创建helloworld.ejs文件, 文件中输入如下内容

<html>
<head>
<title></title>
</head>
<body>
<p>
   <%= title %>
</p>
</body>
</html>
Save the file, go to your command prompt, ctrl-c to kill app.js if it's already running, and then type:
保存页面, 转到命令窗口, CTRL + C杀死app.js. (如果应用正在运行), 重新输入node app.js启动.

D: 第4步: http://localhost:3000/helloworld and enjoy the completely asinine text that gets displayed: 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值