创建一个Node.js的服务器,实现客户端向服务器发送请求,服务器给予响应

//任务说明:创建一个Node.js的服务器,实现客户端向服务器发送请求,服务器给予响应

const http = require('http')    // 1.引入系统模块
const app = http.createServer();    // 2.创建服务器对象

// 3.当客户端发送请求的时候  require(请求) response(请求响应对象
app.on('request',(req,res)=>{
    // 4.服务器发出响应
    res.end('<h1>hello,word!</h1>')

})
// localhost
// 监听端口号
// require('utf-8');
app.listen(3000);
console.log('我的服务器已经启动,监听3000端口,请访问localhost:3000');

// app.on()为服务器对象app,添加request请求事件
// 第1个参数:为事件名称
// 第2个参数:为事件处理函数
// req:表示请求对象,存储相关的请求信息,包含请求的地址,请求的方式
// res:响应对象,对客户端发送的请求进行响应,res.end()对象请求进行响应



 安装模块:

 npm i nodemon -g

切换:

npm i nrm -g

 使用镜像:

nrm use taobao

若是报错,复制如下:

set-ExecutionPolicy RemoteSigned 

跑起来

 nodemon app.js

 

自行复习http协议和请求消息的GET和POST

在第8行下面新增代码,写入到第9行:

console.log(req.method);

 代码如下:

//任务说明:创建一个Node.js的服务器,实现客户端向服务器发送请求,服务器给予响应

const http = require('http')    // 1.引入系统模块
const app = http.createServer();    // 2.创建服务器对象

// 3.当客户端发送请求的时候  require(请求) response(请求响应对象
app.on('request',(req,res)=>{
    // 6.打印获取请求方式
    console.log(req.method);
    // 4.服务器发出响应
    res.end('<h1>hello,word!</h1>')

})
// localhost
// 5.监听端口号

app.listen(3000);
console.log('我的服务器已经启动,监听3000端口,请访问localhost:3000');

// app.on()为服务器对象app,添加request请求事件
// 第1个参数:为事件名称
// 第2个参数:为事件处理函数
// req:表示请求对象,存储相关的请求信息,包含请求的地址,请求的方式
// res:响应对象,对客户端发送的请求进行响应,res.end()对象请求进行响应



 


创建form.html文件,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="http://localhost:3000" method="post">
        <input type="submit" name="submit">
    </form>
</body>
</html>

 点击运行,浏览器此时打开的是html文件,html里面点击"提交"按钮之后,会打开刚刚的localhost:3000,然后刷新浏览器

回到vsc查看终端效果如下:

 ​​​​​​


新增代码如下:

//任务说明:创建一个Node.js的服务器,实现客户端向服务器发送请求,服务器给予响应

const http = require('http')    // 1.引入系统模块
const app = http.createServer();    // 2.创建服务器对象

// 3.当客户端发送请求的时候  require(请求) response(请求响应对象
app.on('request',(req,res)=>{
    // 6.打印获取请求方式
    console.log(req.method);
    // 7.根据 请求方式的不同,响应不同的内容
    if(req.method == 'POST'){
        res.end('POST')
    }else if(req.method == 'GET'){
        res.end('GET')
    }
    // 4.服务器发出响应
    res.end('<h1>hello,word!</h1>')

})
// localhost
// 5.监听端口号

app.listen(3000);
console.log('我的服务器已经启动,监听3000端口,请访问localhost:3000');

// app.on()为服务器对象app,添加request请求事件
// 第1个参数:为事件名称
// 第2个参数:为事件处理函数
// req:表示请求对象,存储相关的请求信息,包含请求的地址,请求的方式
// res:响应对象,对客户端发送的请求进行响应,res.end()对象请求进行响应



刷新localhost:3000页面,运行效果如下:


新建文件server.js代码如下:

//任务说明:创建一个Node.js的服务器,实现客户端向服务器发送请求,服务器给予响应

const http = require('http');    // 1.引入系统模块
const { allowedNodeEnvironmentFlags } = require('process');
const app = http.createServer();    // 2.创建服务器对象

// 3.当客户端发送请求的时候  require(请求) response(请求响应对象

app.on('request',(req,res)=>{
    // 4.根据客户端地址访问的不同内容
    console.log(req.url);
})
// 5.监听端口号

app.listen(3000);
console.log('我的服务器已经启动,监听3000端口,请访问localhost:3000');




根据客户端地址不同获取内容代码如下:

通过res.end()来更换内容welcome to homepage 

//任务说明:创建一个Node.js的服务器,实现客户端向服务器发送请求,服务器给予响应

const http = require('http');    // 1.引入系统模块
const { allowedNodeEnvironmentFlags } = require('process');
const app = http.createServer();    // 2.创建服务器对象

// 3.当客户端发送请求的时候  require(请求) response(请求响应对象

app.on('request',(req,res)=>{
    // 4.根据客户端地址访问的不同内容
    var url = req.url;                   //此处是获取的是完整的网址,包含查询字符串
    
    // 返回结果为完整的URL   /list?url=username&pass=password
    //  当url是"/"或是"/index"时,返回welcome to  homepage
    //   /list  返回 no found
    if(url == '/index' || url == '/'){
        res.end("welcome to  homepage")
    }else if(url =='/list'){
        res.end('not found')
    }


})
// 5.监听端口号

app.listen(3000);
console.log('我的服务器已经启动,监听3000端口,请访问localhost:3000');



 效果如下:


 添加请求响应头代码如下:

//任务说明:创建一个Node.js的服务器,实现客户端向服务器发送请求,服务器给予响应

const http = require('http');    // 1.引入系统模块
const { allowedNodeEnvironmentFlags } = require('process');
const app = http.createServer();    // 2.创建服务器对象

// 3.当客户端发送请求的时候  require(请求) response(请求响应对象

app.on('request',(req,res)=>{
    // 4.根据客户端地址访问的不同内容
    var url = req.url;                   //此处是获取的是完整的网址,包含查询字符串
    
    // 返回结果为完整的URL   /list?url=username&pass=password
    //  当url是"/"或是"/index"时,返回welcome to  homepage
    //   /list  返回 no found
    // if(url == '/index' || url == '/'){
    //     res.end("welcome to  homepage")
    // }else if(url =='/list'){
    //     res.end('not found')
    // }
    // 5.获取请求头
    const headers = req.headers;
    console.log(headers['accept']);
    // console.log(headers['host']);
    res.writeHead(200,{
        'content-type':'text/html;charset=utf8'
    })
    res.end('你好呀,槿花荣!')
})
// 5.监听端口号

app.listen(3000);
console.log('我的服务器已经启动,监听3000端口,请访问localhost:3000');



 解析url

//任务说明:创建一个Node.js的服务器,实现客户端向服务器发送请求,服务器给予响应

const http = require('http');    // 1.引入系统模块
const app = http.createServer();    // 2.创建服务器对象
const URL = require('url')

// 3.当客户端发送请求的时候  require(请求) response(请求响应对象
app.on('request',(req,res)=>{
    console.log(req.url);
    console.log(URL.parse(req.url,true)); //解析url参数,true查看参数解析成对象的形式
    let {query,pathname} = URL.parse(req.url,true);     //通过解构赋值的方式,将解析后的URL参数中的query和pathname属性提取出来。query是一个包含了解析后的查询参数的对象,pathname是请求的URL路径名部分
    console.log(query.pass);    //使用console.log(query.pass)打印出解析后的URL参数对象中的pass字段的值。这样可以查看请求中是否包含了名为pass的参数,并输出其值。
})  
// 5.监听端口号

app.listen(3000);
console.log('我的服务器已经启动,监听3000端口,请访问localhost:3000');


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 好的,以下是一个简单的 Node.js 代码示例,用于创建一个 Web 服务器: ```javascript const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); ``` 以上代码将创建一个基本的 Web 服务器,监听本地主机(127.0.0.1)的 3000 口。当有请求发送到该口时,服务器响应一个 HTTP 状态码为 200 的响应,并将其设置为纯文本的“Hello World”消息。 请注意,这只是一个基本示例,您可以根据需要进行修改和扩展,例如添加路由、处理静态文件等。 ### 回答2: 以下是一个使用Node.js创建web服务器的简单代码示例: ```javascript // 导入所需的模块 const http = require('http'); // 创建一个HTTP服务器 const server = http.createServer((req, res) => { // 设置响应头 res.setHeader('Content-Type', 'text/html'); // 响应内容 res.write('<h1>欢迎访问Node.js服务器!</h1>'); // 结束响应 res.end(); }); // 监听特定口 server.listen(3000, () => { console.log('服务器运行在口3000'); }); ``` 以上代码使用Node.js内置的`http`模块创建了一个基本的HTTP服务器。在创建服务器时,我们传入一个回调函数作为参数,用于处理接收到的请求发送响应。然后,我们设置了响应头的内容类型为`text/html`,并在响应中写入了一个简单的HTML文本。最后,我们使用`listen`方法指定服务器监听的口,并在监听成功后输出一条提示消息到控制台。 要运行以上代码,您可以将其保存为一个独立的文件(例如`server.js`),然后在命令行中使用`node server.js`命令来运行它。接下来,您可以在浏览器中访问`http://localhost:3000`来查看服务器响应。 ### 回答3: Node.js是一种基于事件驱动的JavaScript运行时环境,可以用于编写服务器应用程序。下面是一个使用Node.js创建一个简单的Web服务器的示例代码: 首先,需要安装Node.js。然后在命令行中创建一个新的项目文件夹,并进入该文件夹。 接下来,创建一个新的JavaScript文件,例如`server.js`。在这个文件中,需要引入`http`模块和`fs`模块,一个用于创建HTTP服务器对象,另一个用于读取文件。 ```javascript // 导入http和fs模块 const http = require('http'); const fs = require('fs'); // 定义服务器的监听地址和口 const hostname = '127.0.0.1'; const port = 3000; // 创建一个HTTP服务器对象 const server = http.createServer((req, res) => { // 响应头 res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); // 读取html文件 fs.readFile('index.html', (err, data) => { if (err) { console.error(err); res.end('Error reading file'); } else { // 将读取到的html内容发送客户 res.end(data); } }); }); // 启动服务器监听指定的地址和口 server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); ``` 以上代码创建了一个简单的HTTP服务器,监听地址为`127.0.0.1`,口为`3000`。当有HTTP请求到达时,服务器会读取当前目录下的`index.html`文件,并将其内容作为响应发送客户。 在同一个项目文件夹中,可以创建一个`index.html`文件,并输入一些HTML内容,例如: ```html <!DOCTYPE html> <html> <head> <title>Node.js Web Server</title> </head> <body> <h1>Hello, World!</h1> </body> </html> ``` 要运行这个Web服务器,可以在命令行中执行`node server.js`。然后,在浏览器中访问`http://127.0.0.1:3000/`,就可以看到显示的HTML内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值