创建http服务器以及url模块的使用

1.导入http模块
const http =require(‘http’)
2.创建服务对象
const server=http.createServer((request,response)=>{

response.end(‘hello HTTP Server’)
})
3.监听端口,启动服务
sever.listen(9000,()=>{
console.log(‘服务已经启动’)
})
注意:
1.解决中文乱码问题
response.setHeader(‘content-type’,‘text/html;charset=utf-8’)
2.端口被占用
可以使用资源监控器找到占用端口的程序,然后使用任务管理器关闭对应的程序
3.http协议默认端口是80,https协议默认端口是443
提取HTTP报文
request.url:只包含路径和查询字符串
request.method:获取请求方式、
request.httpVerstion:获取http协议的版本号
request.headers:获取http的请求头
提取http的报文的请求体
const http =require(‘http’)
const server=http.createServer((request,response)=>{
let body=‘’
request.on(‘data’,chunk=>{
body+=chunk
})
request.ono(‘end’,()=>{
response.end(‘hello HTTP Server’)
})
})

下面是对url模块的使用讲解

提取url当中的路径和字符串

const http=require('http')
const url=require('url')
const sever=http,createServer((request,response)=>{
let res =url.parse(request.url,true)
let pathname=res.pathname
//获取路径
console.log(pathname)
//查询字符串
response.end('url')

提取url路径和字符串查询的另一种方式

const http=require(‘http’)

const sever=http,createServer((request,response)=>{
let url =new URL(‘http://www.xxx.com/search?a=100’)

})

下面是对http设置响应报文的讲解

在这里插入图片描述

response.statusCode=200(设置响应状态码)
response.statusMessage="陈云龙必成大事’(设置相应状态的描述)
response,setHeader(“content-type”,‘text/html;charset=utf-8’)

response,setHeader(‘Server’,‘Node.js’)//设置服务器的名字

response,setHeader(‘myheader’,‘test test test’)//设置自定义的相应头

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你可以参考下面的示例代码: ```javascript const express = require('express'); const mysql = require('mysql'); const bodyParser = require('body-parser'); const app = express(); const PORT = 3000; // 创建 MySQL 连接池 const pool = mysql.createPool({ host: 'localhost', user: 'root', password: 'password', database: 'mydb', connectionLimit: 10 // 连接池大小,默认为 10 }); // 使用 body-parser 中间件处理 POST 请求参数 app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // 处理 GET 请求 /search app.get('/search', (req, res) => { const { entity, attribute, keyword } = req.query; const sql = `SELECT * FROM ${entity} WHERE ${attribute} = ?`; pool.getConnection((err, connection) => { if (err) throw err; connection.query(sql, [keyword], (error, results) => { connection.release(); if (error) throw error; res.json(results); // 返回 JSON 格式的查询结果 }); }); }); // 监听 3000 端口 app.listen(PORT, () => { console.log(`Server is running on port ${PORT}.`); }); ``` 在这段代码中,我们首先引入了 Express、mysql 和 body-parser 模块,并创建了 Express 应用程序实例。然后创建了一个 MySQL 连接池,并设置了一些配置参数。接着使用 body-parser 中间件处理 POST 请求参数。最后处理了 GET 请求 /search,从 URL 参数中获取实体、属性和关键字,并构造 SQL 语句进行查询。查询结果会以 JSON 格式返回给客户端。最后监听 3000 端口,启动服务器

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值