http 服务器搭建

http 服务器搭建

通过http模块提供的方法可以创建服务器
1 引入http模块 (nodejs内置模块, 可以直接引入)

const http = require('http');
  1. 创建服务器http.createServer() 方法
  2. response.end() 方法 返回数据 终止响应
  3. 服务要想正常开启,必须要有一个专用的端口号(通道), 默认nodejs的服务端口号是 3000
  4. 回调函数 为了提示服务器正常开启

服务器的搭建写法有好几种:

  • 第一种

const http = require('http');
//  2. 创建服务器 http.createServer() 方法
//  request对象:客户端向服务器请求(传递的所有的数据等信息)  简写  req
//  response对象: 服务器向客户端进行响应(服务器返回的数据等信息)  简写 res

http.createServer((request, response) => {
    
    
    response.end("hello word ");
  //3.  response.end() 方法 返回数据 终止响应 
  //4. 服务要想正常开启,必须要有一个专用的端口号(通道), 默认nodejs的服务端口号是 3000
}).listen(3000, () => {
    
    
//  5. 回调函数 为了提示服务器正常开启
    console.log("server is running at 127.0.0.1 ");
})
  • 第二种
const http = require('http');
const server= http.createServer((request, response) => {
    
    
    response.end("hello word ");
})

server=listen(3000, () => {
    
    
    console.log("server is running at 127.0.0.1 ");
})

有很多条数据时用response.write

上面的写法通过response.end结束服务器响应,只能写入一条信息,当有很多条信息时,需要用另一种方法

const http = require('http');
const server = http.createServer((request, response) => {
    
    
    response.write("hello word")
    response.write("hello word")
    response.write("hello word")
    response.write("hello word")

    response.end();
})
server.listen(3000, () => {
    
    
    console.log("server is running at 127.0.0.1 ");
})

测试服务器是否开启

在自己所建的目录文件夹内 按住Shift+鼠标右键 在菜单内选择“在此处打开命令”
在这里插入图片描述

打开命令窗口后在命令行内输入node 文件名 按回车键弹出代码中监听所输出的内容就代表已经打开服务器
在这里插入图片描述
代码中的内容要输出到页面,打开浏览器输入localhost:3000,回车后就可以在页面中看到代码输出的内容
在这里插入图片描述
代码内的输出内容每改变一次就要在命令窗口重新输入一边node 文件名命令
在这里插入图片描述
在这里插入图片描述
代码中出现中文,在页面输出会出现乱码情况

解决中文乱码问题 设置响应头(设置编码格式和文件的MIME类型)

 response.writeHead(200, {
    
     'Content-type': "text/plain;charset=utf-8" })

200 是http状态码 (代码成功)

{'Content-type':"text/plain;charset=utf-8"}响应头

text/plain (默认是纯文本) 文件的MIME类型 常用的MIME类型:text/html text/css text/image

MIME多用途互联网邮件扩展类型。是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。

 response.writeHead(200, {
    
     'Content-type': "text/plain;charset=utf-8" })
const http = require('http');
const server = http.createServer((request, response) => {
    
    
    response.writeHead(200, {
    
     'Content-type': "text/plain;charset=utf-8" })
    response.write("hello word")
    response.write("hello word")
    response.write("hello word")
    response.write("hello word")
    response.write('你好')
    response.write('<h1>这是h1标签</h1>')

    response.end();
})
server.listen(3000, () => {
    
    
    console.log("server is running at 127.0.0.1 ");
})

在这里插入图片描述

//把MIME类型改变可以改变,可以根据需求读取不同类型
 response.writeHead(200, {
    
     'Content-type': "text/html;charset=utf-8" })

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_53125457/article/details/114917369